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) {
unordered_map<RandomListNode *,RandomListNode *> old2newmap;
RandomListNode *newhead = new RandomListNode(-1);
RandomListNode *temp = head;
RandomListNode *cur = newhead;
while(temp) {
RandomListNode *newNode = new RandomListNode(temp->label);
old2newmap[temp] = newNode;
cur->next = newNode;
cur = cur->next;
temp = temp->next;
}
temp = head;
while(temp) {
if(temp->random) {
old2newmap[temp]->random = old2newmap[temp->random];
}
temp = temp->next;
}
return newhead->next;
}
};
本文介绍了一种复杂链表结构的深拷贝方法,这种链表除了常规的next指针外还包含了一个指向链表中任意节点或null的随机指针。通过使用哈希映射的方法,确保了新链表的独立性和正确性。
1273

被折叠的 条评论
为什么被折叠?



