zoukankan      html  css  js  c++  java
  • Copy List with Random Pointer

    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.

     1 RandomListNode* result;
     2         if (!head) return result;
     3         
     4         // copy each node in the original list
     5         RandomListNode* move = head;
     6         while (move) {
     7             RandomListNode* temp = new RandomListNode(move->label);
     8             temp->next = move->next;
     9             move->next = temp;
    10             move = move->next->next;
    11         }
    12         
    13         // specify the random pointer of each new node
    14         move = head;
    15         while (move) {
    16             if (move->random) 
    17                 move->next->random = move->random->next;
    18             move = move->next->next;
    19         }
    20         
    21         // break the list into two and return the new one
    22         move = head;
    23         RandomListNode* newHead = head->next;
    24         RandomListNode* moveNew = newHead;
    25         while (move) {
    26             move->next = move->next ? move->next->next : NULL;
    27             moveNew->next = moveNew->next ? moveNew->next->next : NULL;
    28             move = move->next;
    29             moveNew = moveNew->next;
    30         }
    31         
    32         return newHead;
  • 相关阅读:
    misc子系统
    Spring boot+RabbitMQ环境
    Linux input
    lnmp环境的搭建
    DDD的.NET开发框架
    【踩坑记】从HybridApp到ReactNative
    Migrating from IntelliJ Projects
    Windows下Redis中RedisQFork位置调整
    远程仓库版本回退方法 good
    maven repository
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5786116.html
Copyright © 2011-2022 走看看