牛客网-剑指Offer-复杂链表的复制

题目链接:https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

看了半天没看懂什么意思,原来就是复制一个链表,但是地址不能和原来相同。

主要涉及指针的理解。

 1 class Solution {
 2 public:
 3     RandomListNode* Clone(RandomListNode* pHead)
 4     {
 5         if(pHead == NULL)
 6             return NULL;
 7 
 8         map<RandomListNode* , RandomListNode* > mp;
 9         RandomListNode* cur = pHead;
10         RandomListNode* res = pHead;
11 
12         while(cur)
13         {
14             mp[cur] = new RandomListNode(cur->label);
15             cur = cur->next;
16         }
17 
18         while(pHead)
19         {
20             cur = mp[pHead];
21             cur->random = mp[pHead->random];
22 
23             if(pHead->next)
24                 cur->next = mp[pHead->next];
25 
26             pHead = pHead->next;
27             cur = cur->next;
28         }
29 
30         return mp[res];
31     }
32 };
View Code

猜你喜欢

转载自www.cnblogs.com/westwind1005/p/10267066.html
今日推荐