Skip to content

Commit 91322b9

Browse files
committed
AC,类似于copy graph
1 parent 7341a1d commit 91322b9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

map_set/Copy List with Random Pointer

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
};

0 commit comments

Comments
 (0)