- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 59 lines of Java from the credited upstream file 148.java.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public ListNode sortList(ListNode head) {3 final int length = getLength(head);4 ListNode dummy = new ListNode(0, head);5 6 for (int k = 1; k < length; k *= 2) {7 ListNode curr = dummy.next;8 ListNode tail = dummy;9 while (curr != null) {10 ListNode l = curr;11 ListNode r = split(l, k);12 curr = split(r, k);13 ListNode[] merged = merge(l, r);14 tail.next = merged[0];15 tail = merged[1];16 }17 }18 19 return dummy.next;20 }21 22 private int getLength(ListNode head) {23 int length = 0;24 for (ListNode curr = head; curr != null; curr = curr.next)25 ++length;26 return length;27 }28 29 private ListNode split(ListNode head, int k) {30 while (--k > 0 && head != null)31 head = head.next;32 ListNode rest = head == null ? null : head.next;33 if (head != null)34 head.next = null;35 return rest;36 }37 38 private ListNode[] merge(ListNode l1, ListNode l2) {39 ListNode dummy = new ListNode(0);40 ListNode tail = dummy;41 42 while (l1 != null && l2 != null) {43 if (l1.val > l2.val) {44 ListNode temp = l1;45 l1 = l2;46 l2 = temp;47 }48 tail.next = l1;49 l1 = l1.next;50 tail = tail.next;51 }52 tail.next = l1 == null ? l2 : l1;53 while (tail.next != null)54 tail = tail.next;55 56 return new ListNode[] {dummy.next, tail};57 }58}59