forked from coderchen/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopyListWithRandomPointer.cpp
71 lines (61 loc) · 1.44 KB
/
CopyListWithRandomPointer.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
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
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
typedef std::map<RandomListNode*, RandomListNode*> NodeMap;
typedef std::vector<RandomListNode*> NodeVec;
typedef std::map<RandomListNode*, NodeVec> UpdateMap;
public:
RandomListNode *copyRandomList(RandomListNode *head) {
NodeMap nodeMap;
UpdateMap updateMap;
RandomListNode* newHead = nullptr;
RandomListNode** pp = &newHead;
while (head) {
RandomListNode* pOld = head;
head = head->next;
RandomListNode* pNew = nullptr;
{
NodeMap::iterator it = nodeMap.find(pOld);
if (it != nodeMap.end()) {
pNew = it->second;
} else {
pNew = new RandomListNode(pOld->label);
nodeMap[pOld] = pNew;
}
*pp = pNew;
pp = &(pNew->next);
}
{
UpdateMap::iterator it = updateMap.find(pOld);
if (it != updateMap.end()) {
NodeVec& v = it->second;
std::for_each(v.begin(), v.end(),
[pNew](RandomListNode* p) {
p->random = pNew;
});
}
}
if (!pOld->random) continue;
{
NodeMap::iterator it = nodeMap.find(pOld->random);
if (it != nodeMap.end()) {
pNew->random = it->second;
} else {
updateMap[pOld->random].push_back(pNew);
}
}
}
return newHead;
}
};
int main()
{
return 0;
}