Sort List

Merge Sort.

public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode slow = head, fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
slow = head;
ListNode first = sortList(slow);
ListNode second = sortList(fast);
return merge(first, second);
}

private ListNode merge(ListNode first, ListNode second) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while(first != null && second != null) {
if(first.val < second.val) {
ListNode next = first.next;
head.next = first;
head = head.next;
head.next = null;
first = next;
} else {
ListNode next = second.next;
head.next = second;
head = head.next;
head.next = null;
second = next;
}
}
if(first != null) {
head.next = first;
} else {
head.next = second;
}
return dummy.next;
}
}


posted @ 2014-12-29 13:30  江南第一少  阅读(93)  评论(0)    收藏  举报