问题:
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.
分析:三次遍历,其中:
第一次:复制每一个node,并插入在对应node后面;
第二次:复制random pointers
第三次:拆分list
代码:
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode *curr = head;
// copy the list
while (curr) {
RandomListNode *temp = new RandomListNode(curr->label);
temp->next = curr->next;
curr->next = temp;
curr = curr->next->next;
}
// copy the random pointers
curr = head;
while (curr) {
curr->next->random = curr->random ? curr->random->next : NULL;
curr = curr->next->next;
}
RandomListNode dummy(0);
RandomListNode *newList = &dummy;
curr = head;
// split the list
while (curr) {
newList->next = curr->next;
curr->next = curr->next->next;
curr = curr->next;
newList = newList->next;
}
return dummy.next;
}
};