[InterviewBit] Copy List

Copy List

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
RandomListNode* Solution::copyRandomList(RandomListNode* A) {
unordered_map<RandomListNode*, RandomListNode*> mp;
RandomListNode* runner = A;
while(runner) {
RandomListNode* copy = new RandomListNode(runner->label);
mp[runner] = copy;
runner = runner->next;
}
runner = A;
while(runner) {
mp[runner]->random = mp[runner->random];
mp[runner]->next = mp[runner->next];
runner = runner->next;
}
return mp[A];
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/26/PS/interviewbit/copy-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.