A linked list is given such this each node contains an additional random pointer which could point to all node in the list or null.
Return a deep copy of the list.
/* * Definition for singly-linked list with a random pointer. * struct RANDOMLISTNODE {* int label; * Randomli Stnode *next, *random; * */
Problem Solving Ideas:
General List deep Copy (not just copy a head, but create a copy of each node) simply create the node and assign value and *next. But the node here contains a *random member who can point to either node or null in the list and need to correspond the *random in the original list to the new list.
My train of thought:
1, first create a new head through new, named as result.
2, deep copy of the original list, regardless of members: random
3, through the definition of two pointers traverse head and result. Search for a member of the Random method: Define the pointer *p *q, they move from head and result at the same time, the source list to move *random items, the destination list is also the corresponding member of the *random.
classSolution { Public: Randomlistnode*copyrandomlist (Randomlistnode *head) { if(head==NULL)returnNULL; Else{Randomlistnode*temp =NewRandomlistnode (Head->label), *ptr,*result; PTR=Head; Result=temp; while(ptr->next!=NULL) {Temp->next =NewRandomlistnode (ptr->next->label); PTR= ptr->Next; Temp= temp->Next; } ptr=Head; Temp=result; while(ptr!=NULL) { if(ptr->random!=NULL) {Randomlistnode*p=head, *q=result; while(p->next!=NULL) { if(p==ptr->random) {Temp->random =Q; Break; } P= p->Next; Q= q->Next; } temp->random =Q; } ptr= ptr->Next; Temp= temp->Next; } returnresult; } }};
Other ideas (better):
1, insert a new node behind each node, the node label,random is a copy of the previous node
2. Random = random->next; of the new node
3. Make a list of newly created nodes sequentially
classSolution { Public: Randomlistnode*copyrandomlist (Randomlistnode *head) {Randomlistnode*thead =Head; Randomlistnode*next =NULL; while(tHead) {Next= thead->Next; Randomlistnode*node =NewRandomlistnode (thead->label); Node->next = thead->Next; //node->random = thead->random;Thead->next =node; THead=Next; } tHead=Head; while(tHead) {if(thead->random) Thead->next->random = thead->random->Next; THead= thead->next->Next; } Randomlistnode*rethead =NULL; Randomlistnode*tret =NULL; THead=Head; Randomlistnode*NEXT2 =NULL; while(tHead) {if(Rethead = =NULL) {NEXT2= thead->next->Next; Rethead= thead->Next; Tret=Rethead; THead->next =next2; THead=next2; } Else{next2= thead->next->Next; Tret->next = thead->Next; THead->next =next2; THead=next2; Tret= tret->Next; } } returnRethead; }};
Copy List with Random Pointer-leetcode