-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopylistwithrandompointer.cpp
More file actions
55 lines (53 loc) · 1.56 KB
/
copylistwithrandompointer.cpp
File metadata and controls
55 lines (53 loc) · 1.56 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
/**
* 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 == NULL)
{
return NULL;
}
map<RandomListNode*, RandomListNode*> m;
queue<RandomListNode*>q;
q.push(head);
while (!q.empty())
{
auto tmp = q.front();
q.pop();
if (m.count(tmp) == 0)
{
auto newnode = new RandomListNode(tmp->label);
m[tmp] = newnode;
}
auto nextnode = tmp->next;
if (nextnode != NULL)
{
if (m.count(nextnode) == 0)
{
auto nn = new RandomListNode(nextnode->label);
m[nextnode] = nn;
q.push(nextnode);
}
m[tmp]->next = m[nextnode];
}
auto rannode = tmp->random;
if (rannode != NULL)
{
if (m.count(rannode) == 0)
{
auto nn = new RandomListNode(rannode->label);
m[rannode] = nn;
q.push(rannode);
}
m[tmp]->random = m[rannode];
}
}
return m[head];
}
};