File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 关键是random 的处理,可以先将其新建,等next 到这个节点的时候取出新建的再复制其他相关信息 ,这个时候利用了map,可以用boost
2
+ 提供的unorder_map 更加节约时间。
3
+
4
+ class Solution {
5
+ public:
6
+ RandomListNode *copyRandomList(RandomListNode *head) {
7
+ RandomListNode *newhead = new RandomListNode (0);
8
+ RandomListNode *q = newhead;
9
+ RandomListNode *p = head;
10
+ map<RandomListNode*,RandomListNode*> exist;
11
+ while(p)
12
+ {
13
+ if(exist.count(p) == 0)
14
+ {
15
+ RandomListNode* node = new RandomListNode (p->label);
16
+ exist[p] = node;
17
+ }
18
+ exist[p]->next = p->next;
19
+ if(p->random != nullptr)
20
+ {
21
+ if(exist.count(p->random) == 0)
22
+ {
23
+ RandomListNode *random = new RandomListNode(p->random->label);
24
+ exist[p->random] = random;
25
+ }
26
+ exist[p]->random = exist[p->random];
27
+ }
28
+ else
29
+ exist[p]->random = nullptr;
30
+ q->next = exist[p];
31
+ p = p->next;
32
+ q = q->next;
33
+ }
34
+ return newhead->next;
35
+
36
+
37
+ }
38
+ };
You can’t perform that action at this time.
0 commit comments