[LeetCode] 132: Copy List with Random Pointer

[Problem]

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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// null node
if(NULL == head) return head;

// create new nodes of the old list
map<RandomListNode *, int> myMap; // stores the index of the nodes in the old list
vector<RandomListNode *> newNodes; // new nodes
RandomListNode *p = head;
int i = 0, j = 0;
while(p != NULL){
RandomListNode *node = new RandomListNode(p->label);
newNodes.push_back(node);

// stores index and increase index
myMap[p] = i++;
p = p->next;
}

// copy
p = head;
i = 0;
while(p != NULL){
if(p->next != NULL){
newNodes[i]->next = newNodes[i+1];
}
if(p->random != NULL){
newNodes[i]->random = newNodes[myMap[p->random]];
}
i++;
p = p->next;
}
return newNodes[0];
}
};

说明:版权所有,转载请注明出处。 Coder007的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值