版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hy971216/article/details/82831099
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深度拷贝。
对于通常的链表,我们递归依次拷贝就可以了,同时用一个hash表记录新旧节点的 映射关系用以处理random问题
/**
* 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) {
if(head == NULL) {
return NULL;
}
RandomListNode dummy(0);
RandomListNode* n = &dummy;
RandomListNode* h = head;
map<RandomListNode*, RandomListNode*> m;
while(h) {
RandomListNode* node = new RandomListNode(h->label);
n->next = node;
n = node;
node->random = h->random;
m[h] = node;
h = h->next;
}
h = dummy.next;
while(h) {
if(h->random != NULL) {
h->random = m[h->random];
}
h = h->next;
}
return dummy.next;
}
};