原题链接在这里:https://leetcode.com/problems/sort-list/
思路: 1. 递归采用merge sort
2. 通过midList找到中点,从中点和中点后一点断开
3. 前后段分别递归merge sort,一直拆到剩一个点,然后再merge
Note: 1. 必须记得要断开原有list,否则会栈溢出。
2. 若有偶数个点,midList找的是中间一对前面的点。
与 Insertion Sort List属于同一题型。
AC Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode middle = midList(head);
ListNode rightHead = middle.next;
middle.next = null; //error
return mergeList(sortList(head),sortList(rightHead));
}
private ListNode midList(ListNode head){
ListNode runner = head;
ListNode walker = head;
while(runner.next != null && runner.next.next!=null){
runner = runner.next.next;
walker = walker.next;
}
return walker;
}
private ListNode mergeList(ListNode head1, ListNode head2){
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while(head1 != null && head2 != null){
if(head1.val <= head2.val){
cur.next = head1;
head1 = head1.next;
}else{
cur.next = head2;
head2 = head2.next;
}
cur = cur.next;
}
if(head1 != null){
cur.next = head1;
}
if(head2 != null){
cur.next = head2;
}
return dummy.next;
}
}