复制带随机指针的链表
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。挑战
可否使用O(1)的空间
标签
哈希表 链表 优步
code
/**
* 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
RandomListNode * newHead;
map<RandomListNode *, RandomListNode *> mapRandom;
newHead = createListNext(head, mapRandom);
newHead = createListRandom(head, newHead, mapRandom);
return newHead;
}
RandomListNode *createListNext(RandomListNode *head, map<RandomListNode *, RandomListNode *> &mapRandom) {
// write your code here
RandomListNode * newHead;
RandomListNode * p=head, *q;
if(head == NULL)
return NULL;
q = newHead = new RandomListNode(p->label);
mapRandom.insert(pair<RandomListNode *, RandomListNode *>(p, q));
p = p->next;
while(p != NULL) {
q->next = new RandomListNode(p->label);
mapRandom.insert(pair<RandomListNode *, RandomListNode *>(p, q->next));
q = q->next;
p = p->next;
}
return newHead;
}
RandomListNode *createListRandom(RandomListNode *head,RandomListNode *newHead, map<RandomListNode *, RandomListNode *> &mapRandom) {
// write your code here
RandomListNode * p=head;
RandomListNode * q=newHead;
if(head == NULL)
return NULL;
while(p != NULL) {
if(p->random != NULL) {
map<RandomListNode *, RandomListNode *>::iterator it = mapRandom.find(p->random);
q->random = it->second;
}
p = p->next;
q = q->next;
}
return newHead;
}
};