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.
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head == NULL)return NULL;
RandomListNode *p,*newp;
p = head;
while(p != NULL)
{
newp = new RandomListNode(p->label);
newp->next = p->next;
p->next = newp;
p = p->next->next;
}
RandomListNode *h = head->next;
newp = h;
p = head;
while(1)
{
if(p->random)newp->random = p->random->next;
p = p->next->next;
if(!p)break;
newp = newp->next->next;
}
newp = h;
p = head;
while(1)
{
p->next = p->next->next;
if(newp->next)newp->next = newp->next->next;
p = p->next;
newp = newp->next;
if(!newp)break;
}
return h;
}
};
本文介绍了一种解决复杂链表深拷贝问题的方法。这种链表的节点包含常规的下一个节点指针以及额外的随机指针。文章详细展示了如何通过巧妙地插入新节点并调整指针来完成这一任务。
1271

被折叠的 条评论
为什么被折叠?



