-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListwithRandomPointer.cpp
More file actions
56 lines (45 loc) · 1.39 KB
/
CopyListwithRandomPointer.cpp
File metadata and controls
56 lines (45 loc) · 1.39 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
52
53
54
55
56
/**
* 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 *cur_node = head;
RandomListNode *new_head = NULL;
while (cur_node)
{
RandomListNode *temp = cur_node->next;
cur_node->next = new RandomListNode(cur_node->label);
assert(cur_node->next);
cur_node->next->next = temp;
cur_node = temp;
}
cur_node = head;
while (cur_node && cur_node->next)
{
if (cur_node->random)
cur_node->next->random = cur_node->random->next;
cur_node = cur_node->next->next;
}
if (head)
new_head = head->next;
cur_node = head;
while (cur_node && cur_node->next)
{
RandomListNode *temp = cur_node->next;
cur_node->next = cur_node->next->next;
if (temp->next)
{
temp->next = temp->next->next;
}
cur_node = cur_node->next;
}
return new_head;
}
};