首页 > 其他 > 详细

138. Copy List with Random Pointer

时间:2017-02-03 10:42:41      阅读:221      评论:0      收藏:0      [点我收藏+]

138. Copy List with Random Pointer 

  • Total Accepted: 95300
  • Total Submissions: 357941
  • Difficulty: Medium
  • Contributors: Admin

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.

Solution

Map the old list node to the new node.

 1 /**
 2  * Definition for singly-linked list with a random pointer.
 3  * struct RandomListNode {
 4  *     int label;
 5  *     RandomListNode *next, *random;
 6  *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     RandomListNode *copyRandomList(RandomListNode *head) {
12         if(head == NULL) return NULL;
13         unordered_map<RandomListNode*, RandomListNode*> old2new;
14         RandomListNode* tmp = head;
15         RandomListNode* dummy = new RandomListNode(-1);//从dummy开始,
16         RandomListNode* curr = dummy;//很容易建立next指针。curr的next指针只要指向current node即可
17         while(tmp){
18             RandomListNode* newnode = new RandomListNode(tmp -> label);
19             //newnode -> next
20             old2new[tmp] = newnode;
21             curr -> next = newnode;
22             curr = curr -> next;//curr也要往前走,才能完成整个链的链接
23             tmp = tmp -> next;
24         }
25         tmp = head;
26         while(tmp){
27             //old2new[tmp] -> next = old2new[tmp -> next];
28             if(tmp -> random){//要判断current node有无random指针
29                 old2new[tmp] -> random = old2new[tmp -> random];
30             }
31             tmp = tmp -> next;
32         }
33         return dummy -> next;//dummy不能变,否则return的就不是一整个链了
34     }
35 };

 

 

 

 

 

 

 

 

 

 

 

138. Copy List with Random Pointer

原文:http://www.cnblogs.com/93scarlett/p/6362019.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!