Advertisement
1988coder

138. Copy List with Random Pointer

Jan 13th, 2019
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/copy-list-with-random-pointer/
  2.  
  3. //Definition for singly-linked list with a random pointer.
  4. // class RandomListNode {
  5. //     int label;
  6. //     RandomListNode next, random;
  7.  
  8. //     RandomListNode(int x) {
  9. //         this.label = x;
  10. //     }
  11. // };
  12.  
  13. /**
  14.  * Iterative with constant extra space
  15.  *
  16.  * Time Complexity: O(N)
  17.  *
  18.  * Space Complexity: O(1)
  19.  *
  20.  * N = Number of nodes in input list.
  21.  */
  22. class Solution {
  23.     public RandomListNode copyRandomList(RandomListNode head) {
  24.         if (head == null) {
  25.             return null;
  26.         }
  27.  
  28.         RandomListNode current = head;
  29.         while (current != null) {
  30.             RandomListNode nodeCopy = new RandomListNode(current.label);
  31.             nodeCopy.next = current.next;
  32.             current.next = nodeCopy;
  33.             current = nodeCopy.next;
  34.         }
  35.  
  36.         current = head;
  37.         while (current != null) {
  38.             if (current.random != null) {
  39.                 current.next.random = current.random.next;
  40.             }
  41.             current = current.next.next;
  42.         }
  43.  
  44.         RandomListNode dummyNewListHead = new RandomListNode(-1);
  45.         RandomListNode currentNewList = dummyNewListHead;
  46.         current = head;
  47.  
  48.         while (current != null) {
  49.             currentNewList.next = current.next;
  50.             current.next = current.next.next;
  51.             current = current.next;
  52.             currentNewList = currentNewList.next;
  53.         }
  54.  
  55.         return dummyNewListHead.next;
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement