-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.CopyListWithRandomPointer.cpp
More file actions
51 lines (47 loc) · 1.25 KB
/
138.CopyListWithRandomPointer.cpp
File metadata and controls
51 lines (47 loc) · 1.25 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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
// 用map来保存新老结点的关系, 需要额外空间
// 可以用老链表的每个结点后插入新节点的方式来知道新老结点的关系, 避免map
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == NULL) {
return NULL;
}
Node* node = head;
map<Node*, Node*> visited;
while(node != NULL) {
Node* newNode = new Node(node->val);
visited[node] = newNode;
node = node->next;
}
node = head;
Node* newListHead = NULL;
Node* newListTail;
while(node != NULL) {
if(newListHead == NULL) {
newListHead = visited[node];
newListTail = newListHead;
newListTail->random = visited[node->random];
} else {
newListTail->next = visited[node];
newListTail = newListTail->next;
newListTail->random = visited[node->random];
}
node = node->next;
}
return newListHead;
}
};