A linked list is given such that each node contains an additional random pointer which could point to any 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; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { if(head==NULL) return NULL; RandomListNode* p=head; while(p)//复制每个节点 { RandomListNode* tmp=p->next; RandomListNode* newNode=new RandomListNode(p->label); p->next=newNode; newNode->next=tmp; p=tmp; } p=head; while(p)//给复制的节点random赋值 { if(p->random==NULL) p->next->random=NULL; else p->next->random=p->random->next; p=p->next->next; } p=head; RandomListNode* newHead=p->next; RandomListNode* p1=newHead; while(p) { p->next=p1->next; if((p->next)!=NULL) p1->next=p->next->next; p=p->next; p1=p1->next; } return newHead; } };
时间: 2024-10-12 08:45:59