148. Sort List
Key idea: partition sort = find middle + sort left and right + merge(left, right)
class Solution {
public ListNode sortList(ListNode head) {
// stop condition
if(head == null || head.next == null)
return head;
// find middle
ListNode fast = head.next, slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// sort two parts
ListNode head2 = slow.next;
slow.next = null;
ListNode first = sortList(head);
ListNode second = sortList(head2);
//combine two parts
ListNode dump = new ListNode();
ListNode temp = dump;
while(first != null && second != null) {
if(first.val < second.val) {
temp.next = first;
first = first.next;
} else {
temp.next = second;
second = second.next;
}
temp = temp.next;
}
if(first != null)
temp.next = first;
if(second != null)
temp.next = second;
return dump.next;
}
}Last updated