-
Notifications
You must be signed in to change notification settings - Fork 95
/
copy-list-with-random-pointer.cpp
40 lines (40 loc) · 1.12 KB
/
copy-list-with-random-pointer.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 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.
RandomListNode *p = head, *np = NULL, *newHead = NULL;
while(p) {
RandomListNode *newNode = new RandomListNode(p->label);
newNode->next = p->next;
p->next = newNode;
p = newNode->next;
}
p = head;
while(p) {
if(p->random)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
if(p) {
newHead = np = p->next;
p->next = p->next->next;
p = p->next;
}
while(p) {
np->next = p->next;
np = np->next;
p->next = p->next->next;
p = p->next;
}
return newHead;
}
};