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 * src = head;
while(src)
{
RandomListNode * new_node = new RandomListNode(src->label);
new_node->next = src->next;
src->next = new_node;
src = src->next->next;
}
src = head;
while(src!=NULL)
{
if(src->random!=NULL)
src->next->random = src->random->next;
src = src->next->next;
}
src = head;
RandomListNode *dst = src->next;
RandomListNode * Dst = dst;
while(dst->next!=NULL)
{
src->next = src->next->next;
src = src->next;
dst->next = dst->next->next;
dst = dst->next;
}
src->next = src->next->next;
return Dst;
}
};
本文介绍了一种复杂链表的深拷贝方法,该链表除了常规的next指针外还包含指向任意节点的随机指针。通过在原链表中插入新节点并调整指针引用,实现了一次遍历完成深拷贝。
194

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



