Advertisement
Kali_prasad

copy list and return it

Jun 16th, 2022
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * struct RandomListNode {
  4. * int label;
  5. * RandomListNode *next, *random;
  6. * RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
  7. * };
  8. */
  9. RandomListNode* Solution::copyRandomList(RandomListNode* A) {
  10.  
  11. RandomListNode* temp=A;
  12. RandomListNode* temp2=NULL;
  13. RandomListNode* temp3=NULL;
  14. if(A->next==NULL) return temp;
  15.  
  16. while(temp!=NULL)
  17. {
  18. temp2=temp->next;
  19. temp->next=new RandomListNode(temp->label);
  20. temp->next->next=temp2;
  21. temp=temp2;
  22. }//completed duplication
  23.  
  24. temp=A;
  25. temp2=A->next;
  26. temp3=temp2;
  27.  
  28. while(temp!=NULL&&temp2!=NULL)
  29. {
  30.  
  31. temp2->random=temp->random->next;
  32. temp=temp2->next;
  33. temp2=temp->next;
  34.  
  35. }//completed random part
  36.  
  37. temp=A;
  38. temp2=A->next;
  39.  
  40. while(temp!=NULL||temp2!=NULL)
  41. {
  42. temp->next=temp->next->next;
  43. temp2->next=temp2->next->next;
  44. temp=temp->next;
  45. temp2=temp2->next;
  46. }//completed seperation of lists part
  47. /* */
  48. return temp3;
  49.  
  50.  
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement