forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s1.cpp
39 lines (38 loc) · 875 Bytes
/
s1.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
/**
* 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) {}
* };
*/
#include <map>
using namespace std;
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head) return NULL;
RandomListNode *new_head, *p, *q, *prev;
map<RandomListNode*, RandomListNode*> m;
m[NULL] = NULL;
new_head = new RandomListNode(head->label);
m[head] = new_head;
p = head->next;
prev = new_head;
while(p){
q = new RandomListNode(p->label);
m[p] = q;
prev->next = q;
prev = q;
p = p->next;
}
p = head;
q = new_head;
while(p){
q->random = m[p->random];
p = p->next;
q = q->next;
}
return new_head;
}
};