zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    C语言_航模社第四节
    C语言_航模社第三节
    C语言交换两个变量的值
    C语言表达分段函数
    c语言_2017.10.22
    stm32_配置GPIO点亮led灯
    prteus8安装教程
    安装keil_5步骤
    nginx配置实现https的配置文件方法
    TortoiseGit 代码版本回退及返回
  • 原文地址:https://www.cnblogs.com/guyufei/p/3445388.html
Copyright © 2011-2022 走看看