knakul853

Untitled

Jun 17th, 2020
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. /*
  2. knakul853
  3. */
  4.  
  5. class Solution {
  6. public:
  7.     Node* copyRandomList(Node* head) {
  8.        
  9.         // just create a linked list with data .
  10.        
  11.         Node* newNode = new Node(0);
  12.        
  13.         Node* curNode = head;
  14.         while(curNode)
  15.         {
  16.             Node* temp = curNode->next;
  17.            
  18.             curNode->next = new  Node(curNode->val);
  19.             curNode->next->next = temp;
  20.             curNode = temp;
  21.         }
  22.        
  23.         // assign random pointer to the newly created linked list.
  24.        
  25.         curNode = head;
  26.         while( curNode )
  27.         {
  28.             if( curNode->random != NULL )
  29.             {
  30.                 curNode->next->random = curNode->random->next;
  31.             }
  32.             curNode = curNode->next ? curNode->next->next : curNode->next;
  33.         }
  34.        
  35.         // extract the cloned and original linked list.
  36.        
  37.         Node* original = head;
  38.         Node* copy = head ? head->next : head;
  39.        
  40.         Node* temp = copy;
  41.        
  42.         while( original && copy )
  43.         {
  44.             original->next=original->next ? original->next->next : original->next;
  45.             copy->next = copy->next ? copy->next->next : copy->next;
  46.            
  47.             original = original->next;
  48.             copy = copy->next;
  49.         }
  50.        
  51.         return temp;
  52.        
  53.        
  54.        
  55.     }
  56. };
Add Comment
Please, Sign In to add comment