您的位置:首页 > 运维架构

leetcode---copy-list-with-random-pointer---链表

2017-10-29 13:57 447 查看
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.

/**
* 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;

RandomListNode *next = NULL, *p = head;
while(p)
{
next = p->next;
RandomListNode *node = new RandomListNode(p->label);
node->next = p->next;
p->next = node;
p = next;
}

p = head;
while(p)
{
if(p->random)
p->next->random = p->random->next;
p = p->next->next;
}

RandomListNode *next2 = NULL, *newH = NULL, *newP = NULL;
p = head;

while(p)
{
if(!newH)
{
next2 = p->next->next;
newH = p->next;
newP = newH;
p->next = next2;
p = next2;
}
else
{
next2 = p->next->next;
newP->next = p->next;
p->next = next2;
p = next2;
newP = newP->next;
}
}
return newH;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐