• Copy List with Random Pointer [LeetCode]


    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.

     1     RandomListNode *copyRandomList(RandomListNode *head) {
     2         map<RandomListNode *, RandomListNode *> old_to_new;
     3         RandomListNode * current = head;
     4         RandomListNode * new_head = NULL;
     5         RandomListNode * pre = NULL;
     6         while(current != NULL) {
     7             RandomListNode * node = new RandomListNode(current->label);
     8             old_to_new[current] = node;    
     9             if(new_head == NULL){
    10                 new_head = node;
    11                 pre = node;
    12             }else if(pre != NULL){
    13                 pre->next = node;
    14                 pre = pre->next;
    15             }
    16             
    17             current = current->next;
    18         }
    19         
    20         current = head;
    21         RandomListNode * new_current = new_head;
    22         while(current != NULL && new_current != NULL) {
    23             if(current->random != NULL)
    24                 new_current->random = old_to_new[current->random];   
    25             else
    26                 new_current->random = NULL; 
    27             current = current->next;
    28             new_current = new_current->next;
    29         }
    30         return new_head;
    31     }
  • 相关阅读:
    Java学习笔记二.2
    Java学习笔记二.1
    Java学习笔记一
    cookie和session笔记
    编码知识笔记
    新手前端笔记之--css盒子
    新手前端笔记之--初识css
    新手前端笔记之--必备的标签
    新手前端笔记之--初识html标签
    二叉树总结
  • 原文地址:https://www.cnblogs.com/guyufei/p/3445388.html
Copyright © 2020-2023  润新知