Skip to content

Commit 508855e

Browse files
committed
Create Copy_List_With_Random_Pointer.cc
1 parent fd48c74 commit 508855e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Copy_List_With_Random_Pointer.cc

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for singly-linked list with a random pointer.
3+
* struct RandomListNode {
4+
* int label;
5+
* RandomListNode *next, *random;
6+
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
RandomListNode *copyRandomList(RandomListNode *head) {
12+
// Note: The Solution object is instantiated only once and is reused by each test case.
13+
RandomListNode *ret = NULL, *tmp = head, *entry = NULL;
14+
RandomListNode **pCur = &ret;
15+
while (tmp) {
16+
entry = tmp;
17+
tmp = tmp->next;
18+
entry->next = new RandomListNode(entry->label);
19+
entry->next->next = tmp;
20+
}
21+
22+
tmp = head;
23+
while (tmp) {
24+
entry = tmp->next;
25+
if (tmp->random)
26+
entry->random = tmp->random->next;
27+
tmp = entry->next;
28+
}
29+
30+
tmp = head;
31+
while (tmp) {
32+
entry = tmp->next;
33+
*pCur = entry;
34+
tmp->next = entry->next;
35+
tmp = tmp->next;
36+
pCur = &((*pCur)->next);
37+
}
38+
return ret;
39+
}
40+
};

0 commit comments

Comments
 (0)