1. 程式人生 > >牛客網-劍指Offer-複雜連結串列的複製

牛客網-劍指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