Advertisement
1988coder

708. Insert into a Cyclic Sorted List

Nov 18th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. /*
  2. // Definition for a Node.
  3. class Node {
  4.     public int val;
  5.     public Node next;
  6.  
  7.     public Node() {}
  8.  
  9.     public Node(int _val,Node _next) {
  10.         val = _val;
  11.         next = _next;
  12.     }
  13. };
  14. */
  15. /*
  16. Single Pass
  17. Refer: https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/discuss/149374/Java-5ms-One-Pass-and-Two-Pass-Traverse-With-Detailed-Comments-and-Edge-cases!
  18.  
  19. Time Complexity: O(n)
  20. Space Complexity: O(1)
  21. n = number of nodes in the list
  22. */
  23. class Solution {
  24.     public Node insert(Node head, int insertVal) {
  25.         // if start is null, create a node pointing to itself and return
  26.         if (head == null) {
  27.             Node node = new Node(insertVal, null);
  28.             node.next = node;
  29.             return node;
  30.         }
  31.         // is start is NOT null, try to insert it into correct position
  32.         Node cur = head;
  33.         while (true) {
  34.             // case 1A: has a tipping point, still climbing
  35.             if (cur.val < cur.next.val && cur.val <= insertVal && insertVal <= cur.next.val) {
  36.                 insertAfter(cur, insertVal);
  37.                 break;
  38.             // case 1B: has a tipping point, about to return back to min node
  39.             } else if (cur.val > cur.next.val && (cur.val <= insertVal || insertVal <= cur.next.val)) {
  40.                 insertAfter(cur, insertVal);
  41.                 break;
  42.             // case 2: NO tipping point, all flat
  43.             } else if (cur.next == head) {
  44.                 insertAfter(cur, insertVal);
  45.                 break;
  46.             }
  47.             // None of the above three cases met, go to next node
  48.             cur = cur.next;
  49.         }
  50.         return head;
  51.     }
  52.    
  53.     public void insertAfter(Node node, int insertVal) {
  54.         node.next = new Node(insertVal, node.next);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement