-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListWithRandomPointer.cpp
More file actions
84 lines (73 loc) · 2.21 KB
/
Copy pathCopyListWithRandomPointer.cpp
File metadata and controls
84 lines (73 loc) · 2.21 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
A linked list is given such that each node contains an additional random pointer
which could point to any node in the list or null.
Return a deep copy of the list.
*/
/**
* 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) {
if (!head) return NULL;
map<RandomListNode*, RandomListNode*> mp;
mp.clear();
RandomListNode* res = new RandomListNode(0);
RandomListNode* p = head;
RandomListNode* q = res;
while (p) {
RandomListNode* tmp = new RandomListNode(p->label);
q->next = tmp;
mp[p] = tmp;
p = p->next;
q = q->next;
}
p = head;
q = res->next;
while (p) {
if( p->random == NULL) {
q->random = NULL;
}
else {
q->random = mp[p->random];
}
p = p->next;
q = q->next;
}
return res->next;
}
};
//Another 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:
RandomListNode *copyRandomList(RandomListNode *head) {
for (RandomListNode *cur = head; cur; cur = cur->next->next) {
RandomListNode *newNode = new RandomListNode(cur->label);
newNode->next = cur->next;
cur->next = newNode;
}
for (RandomListNode *cur = head; cur; cur = cur->next->next)
if (cur->random)
cur->next->random = cur->random->next;
RandomListNode dummy(0), *curNew = &dummy;
for (RandomListNode *cur = head; cur; cur = cur->next) {
curNew->next = cur->next;
curNew = curNew->next;
cur->next = cur->next->next;
}
return dummy.next;
}
};