在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
使用归并排序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next==null){
return head;
}
ListNode oHead = head;
ListNode pre=null,quick=head,slow=head;
while(quick!=null){
quick = quick.next;
if(quick==null){
break;
}
pre = slow;
slow = slow.next;
quick = quick.next;
}
if(pre!=null){
pre.next = null;
}
ListNode left = sortList(oHead);
ListNode right = sortList(slow);
ListNode result = mergeSort(left,right);
return result;
}
//俩链表合并
private ListNode mergeSort(ListNode head1,ListNode head2){
if(head1==null){
return head2;
}
if(head2==null){
return head1;
}
ListNode head=null,node=null;
while(head1!=null && head2!=null){
ListNode now=null;
if(head1.val < head2.val){
now = head1;
head1 = head1.next;
}else{
now = head2;
head2 = head2.next;
}
if(head == null){
head = now;
node = now;
}else{
node.next = now;
node=now;
}
}
while(head1!=null){
node.next = head1;
node = head1;
head1=head1.next;
}
while(head2!=null){
node.next = head2;
node = head2;
head2 = head2.next;
}
return head;
}
}
3213

被折叠的 条评论
为什么被折叠?



