牛客网-剑指Offer-复杂链表的复制
看了半天没看懂什么意思,原来就是复制一个链表,但是地址不能和原来相同。
主要涉及指针的理解。
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 };