Sort List

Sort a linked list in O(n log n) time using constant space complexity.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode sortList(ListNode head) {
  11. if (head == null || head.next == null)
  12. return head;
  13. // step 1. cut the list to two halves
  14. ListNode prev = null, slow = head, fast = head;
  15. while (fast != null && fast.next != null) {
  16. prev = slow;
  17. slow = slow.next;
  18. fast = fast.next.next;
  19. }
  20. prev.next = null;
  21. // step 2. sort each half
  22. ListNode l1 = sortList(head);
  23. ListNode l2 = sortList(slow);
  24. // step 3. merge l1 and l2
  25. return merge(l1, l2);
  26. }
  27. ListNode merge(ListNode l1, ListNode l2) {
  28. ListNode l = new ListNode(0), p = l;
  29. while (l1 != null && l2 != null) {
  30. if (l1.val < l2.val) {
  31. p.next = l1;
  32. l1 = l1.next;
  33. } else {
  34. p.next = l2;
  35. l2 = l2.next;
  36. }
  37. p = p.next;
  38. }
  39. if (l1 != null)
  40. p.next = l1;
  41. if (l2 != null)
  42. p.next = l2;
  43. return l.next;
  44. }
  45. }