-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyRandomList.cpp
More file actions
44 lines (39 loc) · 951 Bytes
/
copyRandomList.cpp
File metadata and controls
44 lines (39 loc) · 951 Bytes
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
/***** 138. 复制带随机指针的链表 ******/
#include<iostream>
#include<unordered_map>
using namespace std;
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
//哈希表 + 回溯 绝了 通过两条链子往下创建,直到返回nullptr
Node* copyRandomList(Node* head)
{
static unordered_map<Node*, Node*> mapNode;
//使用 unordermap,查找o(1)
if(!head)
{
return nullptr;
}
//即还没有创建
if(mapNode.count(head) == 0)
{
Node* headnew = new Node(head->val);
mapNode[head] = headnew;
headnew->next = copyRandomList(head->next);
headnew->random = copyRandomList(head->random);
}
return mapNode[head];
}
int main()
{
return 0;
}