在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
需要注意的地方
1.利用双指针的快指针和慢指针,让慢指针在循环结束的时候停在中间。保留慢指针的下一个作为新链表,从慢指针切断。
2.归并函数的写法,先建立一个头结点,方便后续的操作同一,再在设两个移动指针再两个链表上面滑动。如果a小,链入a,移动a的指针。对于b同理。当有一个为空时,结束了,但是可能有还不是空的结点存在,我们直接链入那个不为空的结点就行了。
class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next==null) {
return head;
}
ListNode low=head;
ListNode fast=head.next;
while(fast!=null&&fast.next!=null) {
low=low.next;
fast=fast.next.next;
}
ListNode mid=low.next; //the mid of the list
low.next=null; //cut off the list
return sort(sortList(head),sortList(mid));
}
ListNode sort(ListNode n1,ListNode n2) {
ListNode node=new ListNode(0); //head node
ListNode head=node;
while(n1!=null&&n2!=null) {
if(n1.val<n2.val) {
node.next=n1;
n1=n1.next;
}
else {
node.next=n2;
n2=n2.next;
}
node=node.next;
}
node.next=(n1==null?n2:n1); //link the rest
return head.next;
}
}