标签:
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 RandomListNode* result; 2 if (!head) return result; 3 4 // copy each node in the original list 5 RandomListNode* move = head; 6 while (move) { 7 RandomListNode* temp = new RandomListNode(move->label); 8 temp->next = move->next; 9 move->next = temp; 10 move = move->next->next; 11 } 12 13 // specify the random pointer of each new node 14 move = head; 15 while (move) { 16 if (move->random) 17 move->next->random = move->random->next; 18 move = move->next->next; 19 } 20 21 // break the list into two and return the new one 22 move = head; 23 RandomListNode* newHead = head->next; 24 RandomListNode* moveNew = newHead; 25 while (move) { 26 move->next = move->next ? move->next->next : NULL; 27 moveNew->next = moveNew->next ? moveNew->next->next : NULL; 28 move = move->next; 29 moveNew = moveNew->next; 30 } 31 32 return newHead;
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/5786116.html