题目
给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3] 输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目在范围
[0, 5 * 104]
内 -105 <= Node.val <= 105
解答
源代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
return mergeSort(head, null);
}
public ListNode mergeSort(ListNode head, ListNode tail) {
if (head == tail) {
return null;
}
if (head.next == tail) {
head.next = null;
return head;
}
ListNode fast = head, slow = head;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
ListNode head1 = mergeSort(head, slow);
ListNode head2 = mergeSort(slow, tail);
ListNode dummyNode = new ListNode(0);
ListNode temp = dummyNode;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
temp.next = head1;
head1 = head1.next;
} else {
temp.next = head2;
head2 = head2.next;
}
temp = temp.next;
}
if (head1 != null) {
temp.next = head1;
} else {
temp.next = head2;
}
return dummyNode.next;
}
}
总结
用了归并算法,这样做的时间复杂度为O(nlogn)。