复制带随机指针的链表(LeetCode 138)
给定一个单链表,链表中的每个节点包含一个额外的指针,随机指向链表中的其它节点或者指向 null。
请复制整个链表,并返回新链表的头结点。
思路:
(哈希表) O(n)
用哈希表维护新旧链表节点之间的对应关系。
从前往后扫描旧链表,对于每个节点的两条边(next以及random),如果新链表中对应的点还未创建,则创建节点,并将新节点与旧链表中的节点关联起来,然后根据节点之间的映射关系,在新链表中添加这两条边(next以及random)。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return 0;
unordered_map<Node*, Node*> hash;
Node *root = new Node(head->val, NULL, NULL);
hash[head] = root;
while (head->next)
{
if (hash.count(head->next) == 0)
hash[head->next] = new Node(head->next->val, NULL, NULL);
hash[head]->next = hash[head->next];
if (head->random && hash.count(head->random) == 0)
hash[head->random] = new Node(head->random->val, NULL, NULL);
hash[head]->random = hash[head->random];
head = head->next;
}
if (head->random && hash.count(head->random) == 0)
hash[head->random] = new Node(head->random->val, NULL, NULL);
hash[head]->random = hash[head->random];
return root;
}
};