一开始没读懂题,不知道要干什么,看了评论之后才知道。
看了别人的解题思路,自己实现了一下。
遇到的错误
Random pointer of node with label 13 points to a node from the original list
好像还没大有人遇到这个错误,在网上搜不到相同的内容。错误很直接的提示了,翻译过来就是某一个复制后的节点的random指向了原节点
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == NULL)
return head;
Node* p = head;
while(p != NULL)
{
Node* temp = new Node(p->val);
temp->next = p->next;
p->next = temp;
p = temp->next;
}
p = head;
while(p != NULL)
{
if(p->random != NULL)
p->next->random = p->random->next; //若p->next->random = p->random;
//则会出现上文的错误
p = p->next->next;
}
p = head;
Node* r = head->next;
Node* rp = r;
while(rp->next != NULL)
{
p->next = rp->next;
p = p->next;
rp->next = p->next;
rp = rp->next;
}
p->next = NULL;
return r;
}
};