题目描述
现在有一个这样的链表:链表的每一个节点都附加了一个随机指针,随机指针可能指向链表中的任意一个节点或者指向空。
请对这个链表进行深拷贝。
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.
思路
三步走:
- 插入节点
- 复制随机指针
- 拆分链表
注意事项:这里的while可以用for来写,会更清爽一点。写了while就要注意每次的后移操作,一般报超时的错的时候,可能就是这个问题。总而言之,还是细节的考究!
代码
/**
* 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) return head;
auto cur = head;
RandomListNode* p;
while(cur){
p =new RandomListNode(cur->label);
p->next = cur->next;
cur->next = p;
cur = p->next;
}
//随机指针的复制
cur =head;
while(cur){
p = cur->next;
p->random = (cur->random?cur->random->next:nullptr);
cur = p->next;
}
cur =head;
auto newhead = cur->next;
while(cur){
p=cur->next;
cur = cur->next = p->next;
p->next = (cur?cur->next:nullptr);
}
return newhead;
}
};
for版本
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode *copy,*p;
if (!head) return NULL;
for(p=head;p;p=p->next){
copy = new RandomListNode(p->label);
copy->next = p->next; // insert new at old next
p = p->next = copy;
}
for(p=head;p;p=copy->next){
copy = p->next; // copy random point
copy->random = (p->random?p->random->next:NULL);
}
for(p=head,head=copy=p->next;p;){
p = p->next = copy->next; // split list
copy = copy->next = (p?p->next:NULL);
}
return head;
}