[leetcode]Copy List with Random Pointer
來源:互聯網
上載者:User
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
RandomListNode *p = head;
while (p != NULL) {
RandomListNode *t = new RandomListNode(p->label);
t->next = p->next;
p->next = t;
p = t->next;
}
p = head;
while (p != NULL) {
if (p->random != NULL)
p->next->random = p->random->next;
else
p->next->random = NULL;
p = p->next->next;
}
RandomListNode *new_head, *new_tail;
new_head = new_tail = NULL;
p = head;
while (p != NULL) {
if (new_head == NULL) {
new_head = new_tail = p->next;
} else {
new_tail->next = p->next;
new_tail = p->next;
}
p->next = p->next->next;
p = p->next;
}
if (new_tail != NULL)
new_tail->next = NULL;
return new_head;
}
};