Copy List with Random Pointer -leetcode
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) {} * }; */
解题思路:
一般列表deep copy(不只是copy一个head,而是对每个node的创建复制) 只需创建节点并把value和*next赋值即可。但是这里的node 包含一个*random成员,他可以随意指向列表中的任何一个node或者NULL,需要将原列表中的*random对应到新的列表中。
我的思路:
1、先通过new创建一个新的head,取名为 result。
2、deep copy 原列表,不考虑成员: random
3、通过定义两个指针遍历 head和result。寻找某个成员random的方法:定义指针*p *q,他们从head和result同时移动,源列表中移动*random 项,则目的列表的也是对应成员的*random。
class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { if(head==NULL) return NULL ; else { RandomListNode *temp =new RandomListNode (head->label) , *ptr,*result; ptr=head; result=temp; while(ptr->next!=NULL){ temp->next = new RandomListNode (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; } return result; } } };
其他思路(更好):
1、 在每个节点后面插入一个新的节点,这个节点label,random是前一个节点的拷贝
2、将新节点的random = random->next;
3 、将新创建的节点按序组成一个链表
class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { RandomListNode *tHead = head; RandomListNode *next = NULL; while(tHead) { next = tHead->next; RandomListNode *node = new RandomListNode(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; } } return retHead; } };
梦想不是浮躁,而是沉淀和积累