Advertisement
1988coder

148. Sort List

Nov 4th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  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. /*
  10. Refer: https://leetcode.com/problems/sort-list/discuss/46712/Bottom-to-up(not-recurring)-with-o(1)-space-complextity-and-o(nlgn)-time-complextity
  11.  
  12. Time Complexity: O(n logn)
  13. Outer for loop runs for log n times. Inner while loop runs for 2 * n times.
  14.  
  15. Space Complexity: O(1)
  16. This algorithm uses constant space.
  17. */
  18. class Solution {
  19.     public ListNode sortList(ListNode head) {
  20.         if (head == null || head.next == null) {
  21.             return head;
  22.         }
  23.        
  24.         ListNode cur = head;
  25.         int length = 0;
  26.         while (cur != null) {
  27.             length++;
  28.             cur = cur.next;
  29.         }
  30.        
  31.         ListNode dummyNode = new ListNode(Integer.MIN_VALUE);
  32.         dummyNode.next = head;
  33.         for (int step = 1; step < length; step <<= 1) {
  34.             cur = dummyNode.next;
  35.             ListNode tail = dummyNode;
  36.             while (cur != null) {
  37.                 ListNode left = cur;
  38.                 ListNode right = split(left, step);
  39.                 cur = split(right, step);
  40.                 tail = merge(tail, left, right);
  41.             }
  42.         }
  43.        
  44.         return dummyNode.next;
  45.     }
  46.    
  47.     public ListNode split(ListNode head, int n) {
  48.         for (int i = 1; i < n && head != null; i++) {
  49.             head = head.next;
  50.         }
  51.         if (head == null) {
  52.             return null;
  53.         }
  54.         ListNode next = head.next;
  55.         head.next = null;
  56.         return next;
  57.     }
  58.    
  59.     public ListNode merge(ListNode head, ListNode l1, ListNode l2) {
  60.         while (l1 != null && l2 != null) {
  61.             if (l1.val <= l2.val) {
  62.                 head.next = l1;
  63.                 l1 = l1.next;
  64.             } else {
  65.                 head.next = l2;
  66.                 l2 = l2.next;
  67.             }
  68.             head = head.next;
  69.         }
  70.         head.next = l1 == null ? l2 : l1;
  71.         while (head.next != null) {
  72.             head = head.next;
  73.         }
  74.         return head;
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement