148. Sort List
Sort a linked list in O(nlogn) time using constant space complexity
Thoughts:
Equivalent to write a merge-sort in LinkedList
Recursively (O(logn) stack space complexity): halve the list by setting fast-slow pointers
Iteratively: have two pointer slow, fast, moved by steps a, b to partition the merge list then merge list inside. Repeat the step and shift blocksize value left by 1-bit until no more element left to be merged.
Code: Recursively (java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
// step 1. cut the list to two halves
ListNode prev = null, slow = head, fast = head;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
// step 2. sort each half
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
// step 3. merge l1 and l2
return merge(l1, l2);
}
public ListNode merge (ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
// ListNode head = l1.val > l2.val? l2: l1;
ListNode head;
if(l1.val > l2.val){
head = l2;
l2 = l2.next;
}else{
head = l1;
l1 = l1.next;
}
ListNode cur = head;
while(l1!=null && l2!= null){
if(l1.val > l2.val){
cur.next = l2;
l2 = l2.next;
}else{
cur.next = l1;
l1 = l1.next;
}
cur = cur.next;
}
// deal with the rest nodes
if(l1 != null) cur.next = l1;
if(l2 != null) cur.next = l2;
return head;
}
}Code: Iterative
Last updated
Was this helpful?