# LeetCode 138 复制带随机指针的链表

val：一个表示 Node.val 的整数。
random_index：随机指针指向的节点索引（范围从 0 到 n-1）；如果不指向任何节点，则为  null 。

-10000 <= Node.val <= 10000
Node.random 为空（null）或指向链表中的节点。

c++代码如下：

``` 1 class Solution {
2 public:
3     Node* copyRandomList(Node* head) {
5         auto p = head;
6         while(p){
7             auto q = new Node(p->val);
8             q->next = p->next;
9             p->next = q;
10             p = q->next;
11         }
12         auto k = head;
13         while(k){
14             if(k->random) k->next->random = k->random->next;
15             k = k->next->next;
16         }
17         auto copy = head->next;
18         auto a = head, b = head->next->next;
19         while(b){
20             a->next->next = b->next;
21             a->next = b;
22             a = b;
23             b = b->next->next;
24         }
25         a->next = b;
26         return copy;
27     }
28 };```

``` 1 class Solution {
2 public:
3     Node* copyRandomList(Node* head) {
5         for(auto p = head; p; p = p->next->next){
6             auto q = new Node(p->val);
7             q->next = p->next;
8             p->next = q;
9         }
10
11         for(auto k = head; k; k = k->next->next){
12             if(k->random) k->next->random = k->random->next;
13         }
14         auto dummy = new Node(-1);
15         auto cur = dummy;
16         for(auto p = head; p;p = p->next){
17             cur->next = p->next;
18             p->next = cur->next->next;
19             cur = cur->next;
20         }
21
22         return dummy->next;
23     }
24 };```

LeetCode 138 复制带随机指针的链表

(0)
(0)

© 2014 mamicode.com 版权所有 京ICP备13008772号-2