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

Copy List with Random Pointer

2015-08-13 13:50 453 查看
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.

Solution:

/**
* 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) {
RandomListNode *res = new RandomListNode(-1);
unordered_map<RandomListNode*, int> umRI;
unordered_map<int, RandomListNode*> umIR;
RandomListNode *p = head, *q = res;
int num = 0;
while(p)
{
RandomListNode* node = new RandomListNode(p->label);
q->next = node;
q = q->next;
umIR[++num] = q;
umRI[p] = num;
p = p->next;
}
q->next = NULL;
p = head;
q = res->next;
while(p)
{
if(!p->random) q->random = NULL;
else
{
num = umRI[p->random];
q->random = umIR[num];
}
p = p->next;
q = q->next;
}

return res->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: