您的位置:首页 > 运维架构

Copy List with Random Pointer

2016-08-19 03:15 316 查看
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.

RandomListNode* result;
if (!head) return result;

// copy each node in the original list
RandomListNode* move = head;
while (move) {
RandomListNode* temp = new RandomListNode(move->label);
temp->next = move->next;
move->next = temp;
move = move->next->next;
}

// specify the random pointer of each new node
move = head;
while (move) {
if (move->random)
move->next->random = move->random->next;
move = move->next->next;
}

// break the list into two and return the new one
move = head;
RandomListNode* newHead = head->next;
RandomListNode* moveNew = newHead;
while (move) {
move->next = move->next ? move->next->next : NULL;
moveNew->next = moveNew->next ? moveNew->next->next : NULL;
move = move->next;
moveNew = moveNew->next;
}

return newHead;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: