链接:https://oj.leetcode.com/problems/copy-list-with-random-pointer/
描述:
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.
方法:针对原链表中每个节点,新建一个节点赋予相同的值,然后将新建的节点挂在原链节点的后面。
新建的节点的random指针现在应为,目前新建节点random所指的节点的next节点,指定正确的random节点。
最后将两个链分拆。
代码如下:
RandomListNode *copyRandomList(RandomListNode *head) {
if( head == NULL) return NULL;
RandomListNode *p = head;
while( p )
{
RandomListNode* temp = new RandomListNode(p->label);
temp->next = p->next;
if( p->random)
temp->random = p->random;
p->next = temp;
p = temp->next;
}
p = head->next;
while( p )
{
if( p->random )
p->random = p->random->next;
if(p->next)
p = p->next->next;
else
break;
}
RandomListNode *result = head->next;
RandomListNode *p1 = head;
RandomListNode *p2 = result;
while( p1 && p2)
{
p1->next = p2->next;
p1 = p1->next;
if( p1 ){
p2->next = p1->next;
p2 = p2->next;
}
}
return result;
}