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

Copy List with Random Pointer [LeetCode]

2013-11-27 12:45 381 查看
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.

Solution: Uses map to recorde node mapping between old linked list and new linked list.

RandomListNode *copyRandomList(RandomListNode *head) {
map<RandomListNode *, RandomListNode *> old_to_new;
RandomListNode * current = head;
RandomListNode * new_head = NULL;
RandomListNode * pre = NULL;
while(current != NULL) {
RandomListNode * node = new RandomListNode(current->label);
old_to_new[current] = node;
if(new_head == NULL){
new_head = node;
pre = node;
}else if(pre != NULL){
pre->next = node;
pre = pre->next;
}

current = current->next;
}

current = head;
RandomListNode * new_current = new_head;
while(current != NULL && new_current != NULL) {
if(current->random != NULL)
new_current->random = old_to_new[current->random];
else
new_current->random = NULL;
current = current->next;
new_current = new_current->next;
}
return new_head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: