/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (!head) return NULL;
unordered_map<RandomListNode *, RandomListNode *> map;
RandomListNode *res= new RandomListNode(head->label);
RandomListNode *pre=res;
map[head]=res;
RandomListNode *temp=head->next;
while(temp!=NULL) {
RandomListNode *cur = new RandomListNode(temp->label);
map[temp]=cur;
pre->next=cur;
pre=cur;
temp=temp->next;
}
temp=head;
RandomListNode *cur=res;
while(temp!=NULL) {
RandomListNode *x=map[temp];
RandomListNode *y=map[temp->random];
x->random=y;
temp=temp->next;
}
return res;
}
};If we can modify the original list, there could be another way with the same idea but no need to use a map
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (!head) return NULL;
RandomListNode *res= new RandomListNode(head->label);
RandomListNode *pre=res;
RandomListNode *temp=head->next;
while(temp!=NULL) {
RandomListNode *cur = new RandomListNode(temp->label);
pre->next=cur;
pre=cur;
temp=temp->next;
}
temp=head;
RandomListNode *cur=res;
while(temp!=NULL) {
pre=temp;
temp=temp->next;
pre->next = cur;
cur=cur->next;
}
temp=head;
cur=res;
while(cur!=NULL) {
temp ->next ->random = temp->random;
temp=temp->next;
cur=cur->next;
}
return res;
}
};
本文介绍了一种复制带随机指针的单链表的方法,通过使用哈希映射,实现链表节点及其随机指向节点的高效复制。
1292

被折叠的 条评论
为什么被折叠?



