您的位置:首页 > 运维架构

【LeetCode】Copy List with Random Pointer

2014-04-24 16:18 274 查看
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.

思路:总共分为三个函数来解决,可以参照《剑指offer》4.4的26题。

①先复制所有的节点,把复制的节点直接挂到原始节点后面,所以每两个节点值就是一样的;

②然后将复制的节点的random指针指点前驱节点的random指针指向的下一个节点;

③拆分链表成两个。

/**
* 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:
void CloneList(RandomListNode *head){
RandomListNode *pNode=head;
while(pNode!=NULL){
RandomListNode* tmp=new RandomListNode(pNode->label);
//tmp->label=pNode->label;
tmp->next=pNode->next;
tmp->random=NULL;

pNode->next=tmp;
pNode=tmp->next;
}
}

void CloneRandom(RandomListNode *head){
RandomListNode *pNodeold=head;
while(pNodeold!=NULL){
if(pNodeold->random!=NULL){
pNodeold->next->random=pNodeold->random->next;
}
pNodeold=pNodeold->next->next;
}
}

RandomListNode *DevideList(RandomListNode *head){
RandomListNode *pNodeold=head;
RandomListNode *headnew=NULL;
RandomListNode *pNodenew=NULL;
if(pNodeold!=NULL){
headnew=pNodenew=head->next;
pNodeold->next=pNodenew->next;
pNodeold=pNodeold->next;
}
while(pNodeold!=NULL){
pNodenew->next=pNodeold->next;
pNodenew=pNodenew->next;

pNodeold->next=pNodenew->next;
pNodeold=pNodeold->next;
}
return headnew;
}

RandomListNode *copyRandomList(RandomListNode *head) {
if(head==NULL)return NULL;
CloneList(head);
CloneRandom(head);
return DevideList(head);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: