码迷,mamicode.com
首页 > 其他好文 > 详细

Copy List with Random Pointer

时间:2016-08-19 06:18:25      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 1 RandomListNode* result;
 2         if (!head) return result;
 3         
 4         // copy each node in the original list
 5         RandomListNode* move = head;
 6         while (move) {
 7             RandomListNode* temp = new RandomListNode(move->label);
 8             temp->next = move->next;
 9             move->next = temp;
10             move = move->next->next;
11         }
12         
13         // specify the random pointer of each new node
14         move = head;
15         while (move) {
16             if (move->random) 
17                 move->next->random = move->random->next;
18             move = move->next->next;
19         }
20         
21         // break the list into two and return the new one
22         move = head;
23         RandomListNode* newHead = head->next;
24         RandomListNode* moveNew = newHead;
25         while (move) {
26             move->next = move->next ? move->next->next : NULL;
27             moveNew->next = moveNew->next ? moveNew->next->next : NULL;
28             move = move->next;
29             moveNew = moveNew->next;
30         }
31         
32         return newHead;

 

Copy List with Random Pointer

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5786116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!