首页 > 其他 > 详细

Copy List with Random Pointer

时间:2016-08-19 06:16:50      阅读:174      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!