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     }
  • 相关阅读:
    Python标准模块--logging
    Spark中决策树源码分析
    常见的相似或相异程度计算方法
    mpi4py实践
    集成学习
    决策树
    git使用
    Ubuntu 14.04 64bit 安装tensorflow(GPU版本)
    KNN算法
    一致性哈希算法原理及其在分布式系统中的应用
  • 原文地址:https://www.cnblogs.com/guyufei/p/3445388.html
Copyright © 2011-2022 走看看