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

leetcode Copy List with Random Pointer

2014-06-25 21:31 363 查看
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) {}
* };
*/
/*
该算法更为巧妙,不用保存原始链表的映射关系,构建新节点时,指针做如下变化,即把新节点插入到相应的旧节点后面:

1、构建新节点random指针:new1->random = old1->random->next, new2-random = NULL, new3-random = NULL, new4->random = old4->random->next

2、恢复原始链表以及构建新链表:例如old1->next = old1->next->next, new1->next = new1->next->next

该算法时间复杂度O(N),空间复杂度O(1)*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head==NULL) return NULL;
RandomListNode *old=head;
while(old!=NULL){
RandomListNode *add=new RandomListNode(old->label);
RandomListNode *temp=old->next;
old->next=add;
add->next=temp;
old=temp;
}
old=head;
while(old!=NULL){
if(old->random!=NULL){
old->next->random=old->random->next;
}
old=old->next->next;
}
RandomListNode *dummy=new RandomListNode(INT_MIN);
dummy->next=head;
RandomListNode *n=dummy;
old=head;
while(old!=NULL){
n->next=n->next->next;
old->next=old->next->next;
old=old->next;
n=n->next;
}
n->next=NULL;
return dummy->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: