forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-list-with-random-pointer(AC).cpp
More file actions
51 lines (45 loc) · 1.24 KB
/
copy-list-with-random-pointer(AC).cpp
File metadata and controls
51 lines (45 loc) · 1.24 KB
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
41
42
43
44
45
46
47
48
49
50
51
// Whimsical solution
/**
* 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:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) {
return head;
}
RandomListNode *p, *q;
RandomListNode *h;
p = head;
while (p != NULL) {
q = p->random;
p->random = new RandomListNode(p->label);
p->random->next = q;
p = p->next;
}
p = head;
while (p != NULL) {
q = p->random;
q->random = q->next ? q->next->random : NULL;
p = p->next;
}
h = head->random;
p = head;
while (p != NULL) {
q = p->random;
p->random = q->next;
q->next = p->next ? p->next->random : NULL;
p = p->next;
}
return h;
}
};