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;
  • 相关阅读:
    第十三周编程总结
    第十二周总结
    第十一周课程总结
    第十周编程总结
    第七次实验报告及编程总结
    第六次实验报告及学习总结
    课程总结
    第十四周课程总结&实验报告
    第十三周课程总结
    第十二周总结
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5786116.html
Copyright © 2011-2022 走看看