给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
解法一(参考):
建立哈希表,然后遍历链表,深复制的同时将复制的旧节点作为key,新节点作为value存进哈希表,
第二次遍历 以原链表的一个节点的随机指针值作为索引,查找对应的新链表的对应节点的随机指针值解法二
参考
//哈希表
class Solution {
public:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
map<RandomListNode*,RandomListNode*> hash;
RandomListNode *curr = head;
RandomListNode *newHead = new RandomListNode(curr->label);
RandomListNode * newCurr = newHead;
hash[curr] = newHead;
while(curr->next) {
curr = curr -> next;
RandomListNode *newNode = new RandomListNode(curr->label);
hash[curr] = newNode;
newCurr->next = newNode;
newCurr = newCurr->next;
}
newCurr = newHead;
curr = head;
while(newCurr) {
newCurr->random = hash[curr->random];
newCurr = newCurr->next ;
curr = curr->next;
}
return newHead;
}
};