Copy LinkedList with Random Pointer
易错点分析:
p->random == NULL
的情况;- 先统一设好
copy_p
的random pointer;再用一个循环将original nodes和copied nodes连起来(否则,当random pointer指向已经“恢复”的部分,会发生错误!)切记!
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if ( head == NULL ) return NULL;
RandomListNode* p = head;
while ( p != NULL ) {
RandomListNode* copy_p = new RandomListNode(p->label);
RandomListNode* next = p->next;
p->next = copy_p;
copy_p->next = next;
p = next;
}
p = head;
RandomListNode *copy_p = p->next;
while ( true ) {
if ( p->random == NULL ) copy_p->random = NULL;
else copy_p->random = p->random->next;
if ( copy_p->next == NULL ) break;
p = copy_p->next;
copy_p = p->next;
}
p = head;
copy_p = p->next;
RandomListNode* copy_head = copy_p;
while ( true ) {
if ( copy_p->next == NULL ) {
p->next = NULL;
break;
}
RandomListNode *next = copy_p->next;
RandomListNode *copy_next = next->next;
p->next = next;
copy_p->next = copy_next;
p = p->next;
copy_p = copy_p->next;
}
return copy_head;
}
};