[LeetCode] Copy List with Random Pointer, Solution

 

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

 

[Thoughts]

如图分三步:

1. 插入拷贝节点

2. 复制random指针

3.分解至两个独立列表

 

image

[Code]

   
   
1 RandomListNode * copyRandomList(RandomListNode * head) {
2 // insert nodes
3 RandomListNode * cur = head;
4 while (cur != NULL)
5 {
6 RandomListNode * temp = new RandomListNode(cur -> label);
7 temp -> next = cur -> next;
8 cur -> next = temp;
9 cur = temp -> next;
10 }
11
12 // copy random pointer
13 cur = head;
14 while (cur != NULL)
15 {
16 RandomListNode * temp = cur -> next;
17 if (cur -> random != NULL)
18 temp -> random = cur -> random -> next;
19 cur = temp -> next;
20 }
21
22 // decouple two links
23 cur = head;
24 RandomListNode * dup = head == NULL ? NULL:head -> next;
25 while (cur != NULL)
26 {
27 RandomListNode * temp = cur -> next;
28 cur -> next = temp -> next;
29 if (temp -> next != NULL)
30 temp -> next = temp -> next -> next;
31 cur = cur -> next;
32 }
33
34 return dup;
35 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值