中等 复制带随机指针的链表
27%
通过
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
用了一个哈希表,空间换取时间
/**
* 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:
/**
* @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
if(head == nullptr) {
return nullptr;
}
RandomListNode * fhead = head;
map<RandomListNode*,RandomListNode*> m;
RandomListNode *p = new RandomListNode(head->label);
m.insert(pair<RandomListNode*,RandomListNode*>(head,p));
head = head->next;
RandomListNode *root = p;
while (head!=nullptr) {
p->next = new RandomListNode(head->label);
p = p->next;
m.insert(pair<RandomListNode*,RandomListNode*>(head,p));
head = head->next;
}
p = root;
map<RandomListNode*, RandomListNode*>::iterator iter;
while (fhead!=nullptr) {
if(fhead->random != nullptr) {
iter = m.find(fhead->random);
p->random = iter->second;
}
p=p->next;
fhead = fhead->next;
}
return root;
}
};