在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。
给出 1->3->2->null
,给它排序变成 1->2->3->null
.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
思路:
归并排序
* 根据要求采用先sort再merge的方法,
* 1.首先找到中点,
* 2.然后从中点两端分别sort,
* 3.将两个结果进行merge。
*/
public class Solution {
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//当fast.next.next为空,slow为中点
return slow;
}
public ListNode merge(ListNode head1, ListNode head2) {
//Head1的辅助头结点dummy,因为可能在头部插入
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
tail.next = head1;
head1 = head1.next;
} else {
tail.next = head2;
head2 = head2.next;
}
tail = tail.next;
}
//L2或l1可能还有未处理的结点,直接加在尾部即可
if (head1 != null) {
tail.next = head1;
} else {
tail.next = head2;
}
return dummy.next;
}
/*
public ListNode merge(ListNode l1, ListNode l2) {
// write your code here
ListNode head;//新链表
if(l1 == null){return l2;}
if(l2 == null){return l1;}
if(l1.val < l2.val){
head = l1;
head.next = merge(l1.next,l2);
}else{
head = l2;
head.next = merge(l1,l2.next);
}
return head;
}*/
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMiddle(head);
//需要把左半链表的尾结点的next赋空值
//(断开),用一个变量来记录右半链表的头
ListNode nextPart = null;
if(mid !=null){
nextPart = mid.next;
mid.next = null;//断开
}
ListNode left = sortList(head);
ListNode right = sortList(nextPart);
return merge(left,right);
}
}