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

leetcode - Copy List with Random Pointer

时间:2014-09-02 10:19:24      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   art   div   

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,先遍历一遍链表,创建出复制链表,并且复制链表的next指针已经连接好,同时用一个map存储原结点和新结点的映射关系

2,同时遍历一遍原链表和复制链表,此时关注random指针,根据原结点random指针指向的结点和map表,便可找到对应的复制结点,使复制的random指针指向该复制结点即可

代码:

bubuko.com,布布扣
 1 #include <stddef.h>
 2 #include <map>
 3 
 4 using namespace std;
 5 
 6 struct RandomListNode
 7 {
 8     int label;
 9     RandomListNode *next, *random;
10     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
11 };
12 
13 class Solution {
14 public:
15     RandomListNode *copyRandomList(RandomListNode *head) {
16         if (!head)
17         {
18             return NULL;
19         }
20 
21         map<RandomListNode*, RandomListNode*> original2copy;        
22         RandomListNode *originalCurrent = head->next;
23         RandomListNode *copyHead = new RandomListNode(head->label);
24         RandomListNode *copyCurrent = copyHead;
25 
26         original2copy[head] = copyHead;
27 
28         while (originalCurrent) //先创建copy结点和连接next指针,并记录配对信息
29         {
30             copyCurrent->next = new RandomListNode(originalCurrent->label);
31             copyCurrent = copyCurrent->next;
32             original2copy[originalCurrent] = copyCurrent;
33             originalCurrent = originalCurrent->next;
34         }
35 
36         originalCurrent = head;
37         copyCurrent = copyHead;
38         while (originalCurrent) //连接random指针
39         {
40             if (originalCurrent->random)
41             {
42                 copyCurrent->random = original2copy[originalCurrent->random];
43             }
44 
45             originalCurrent = originalCurrent->next;
46             copyCurrent = copyCurrent->next;
47         }
48 
49         return copyHead;
50     }
51 };
View Code

 

还有

leetcode - Copy List with Random Pointer

标签:style   blog   http   color   os   io   ar   art   div   

原文地址:http://www.cnblogs.com/laihaiteng/p/3950757.html

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