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

[LeetCode] 132: Copy List with Random Pointer

2017-09-10 20:53 330 查看
[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的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: