-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLeetcode_copy-list-with-random-pointer.cc
66 lines (64 loc) · 1.64 KB
/
Leetcode_copy-list-with-random-pointer.cc
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
//http://oj.leetcode.com/problems/copy-list-with-random-pointer/
/**
* 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) {
map<RandomListNode*, RandomListNode*> dm;
RandomListNode* p = head, *lastp = NULL, *newhead = NULL;
while(p)
{
RandomListNode* pnew = new RandomListNode(p->label);
dm.insert(pair<RandomListNode*, RandomListNode*>(p, pnew));
if(p!=head)
{
lastp->next=pnew;
lastp = lastp->next;
}
else
{
newhead = lastp = pnew;
}
p = p->next;
}
p = head;
while(p)
{
dm[p]->random = dm[p->random];
p = p->next;
}
return newhead;
}
};
//SECOND TRIAL
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head)
return head;
unordered_map<RandomListNode*, RandomListNode*>mp;
RandomListNode *p = head, *q = NULL, *pre = NULL;
while(p)
{
q = new RandomListNode(p->label);
mp[p] = q;
p = p->next;
if(pre)
pre->next = q;
pre = q;
}
p = head;
while(p)
{
mp[p]->random = mp[p->random];
p = p->next;
}
return mp[head];
}
};