jayati

138. Copy List with Random Pointer

Sep 4th, 2023
1,066
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.60 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     Node* copyRandomList(Node* head) {
  4.         if (!head) return nullptr;
  5.        
  6.         unordered_map<Node*, Node*> old_to_new;
  7.        
  8.         Node* curr = head;
  9.         while (curr) {
  10.             old_to_new[curr] = new Node(curr->val);
  11.             curr = curr->next;
  12.         }
  13.        
  14.         curr = head;
  15.         while (curr) {
  16.             old_to_new[curr]->next = old_to_new[curr->next];
  17.             old_to_new[curr]->random = old_to_new[curr->random];
  18.             curr = curr->next;
  19.         }
  20.        
  21.         return old_to_new[head];
  22.        
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment