请教leetcode上一道习题

class Solution {public: RandomListNode *copyRandomList(RandomListNode *head) { RandomListNode *dummyHead = new RandomListNode(0); RandomListNode *p = head, *q = dummyHead; // build a map that maps the original node to its indices unordered_map\u0026lt;RandomListNode *, size_t\u0026gt; originalMap; size_t indice = 0; while (p != NULL) { originalMap.insert(make_pair(p, indice++)); p = p-\u0026gt;next; } // clone lists with next pointer p = head; q = dummyHead; while (p != NULL) { q-\u0026gt;next = new RandomListNode(p-\u0026gt;label); p = p-\u0026gt;next; q = q-\u0026gt;next; } // build a map that maps the cloned node\u0026#39;s indice to the pointer which points to itself unordered_map\u0026lt;size_t, RandomListNode *\u0026gt; clonedMap; indice = 0; q = dummyHead-\u0026gt;next; while (q != NULL) { clonedMap.insert(make_pair(indice++, q)); q = q-\u0026gt;next; } // clone lists with random pointer p = head; q = dummyHead-\u0026gt;next; while (p != NULL) { //改动在这里 if (p-\u0026gt;random != NULL) q-\u0026gt;random = clonedMap]; p = p-\u0026gt;next; q = q-\u0026gt;next; } return dummyHead-\u0026gt;next; }};插入random pointer 的地方得判重。
■网友
不会C++ 但是你的 p-\u0026gt;label是什么?从错误信息看你是没有处理特殊情况比如只有一个元素。顺便贴个水中的鱼的正确答案。 【请教leetcode上一道习题】
1 RandomListNode *copyRandomList(RandomListNode *head) { 2 //insert nodes 3 RandomListNode * cur = head; 4 while(cur!=NULL) 5 { 6 RandomListNode* temp = new RandomListNode(cur-\u0026gt;label); 7 temp-\u0026gt;next = cur-\u0026gt;next; 8 cur-\u0026gt;next = temp; 9 cur = temp-\u0026gt;next;10 }11 12 // copy random pointer13 cur = head;14 while(cur != NULL)15 {16 RandomListNode* temp = cur-\u0026gt;next;17 if(cur-\u0026gt;random != NULL)18 temp-\u0026gt;random = cur-\u0026gt;random-\u0026gt;next;19 cur = temp-\u0026gt;next;20 }21 22 //decouple two links23 cur = head;24 RandomListNode* dup = head == NULL? NULL:head-\u0026gt;next;25 while(cur != NULL)26 {27 RandomListNode* temp = cur-\u0026gt;next;28 cur-\u0026gt;next = temp-\u0026gt;next;29 if(temp-\u0026gt;next!=NULL)30 temp-\u0026gt;next = temp-\u0026gt;next-\u0026gt;next;31 cur = cur-\u0026gt;next;32 }33 34 return dup;35 }


    推荐阅读