解法一:
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode fast = head, slow = head;
while(fast != null && fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode temp = slow.next;
slow.next = null;
return mergeList(sortList(head), sortList(temp));
}
public ListNode mergeList(ListNode list1, ListNode list2){
ListNode dummyHead = new ListNode(-1);
ListNode cur = dummyHead;
while(list1 != null && list2 != null){
if (list1.val < list2.val){
cur.next = list1;
list1 = list1.next;
}else{
cur.next = list2;
list2 = list2.next;
}
cur.next.next = null;
cur = cur.next;
}
cur.next = (list1 == null) ? list2 : list1;
return dummyHead.next;
}
}
过不了的代码:不知道为什么会超内存,可能是比解法一递归时多生成了一些变量。
public class Solution {
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
public ListNode sortList(ListNode left, ListNode right){
ListNode fast, slow, sortedLeft, sortedRight, temp;
if (left != null && left.next != null){
fast = left; slow = left;
while(fast != null && fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
temp = slow.next;
slow.next = null;
sortedLeft = sortList(left, temp); // sort the left half
}else
sortedLeft = left;
if (right != null && right.next != null){
fast = right; slow = right;
while(fast != null && fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
temp = slow.next;
sortedRight = sortList(right, temp); // sort the right half
}else
sortedRight = right;
ListNode formHead = new ListNode(-1);
formHead.next = sortedLeft;
ListNode cur = formHead;
while(cur.next != null && sortedRight != null){
while(cur.next != null && cur.next.val <= sortedRight.val){
cur = cur.next;
}
//sortedRight should be insert behind cur
temp = sortedRight.next;
sortedRight.next = cur.next;
cur.next = sortedRight;
cur = (cur.next.next == null) ? cur.next : cur.next.next; //cur.next.next may be null, don't make that happen
sortedRight = temp;
}
if (cur.next == null){
cur.next = sortedRight;
}
return formHead.next;
}
}