zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    这题用map做其实比较简单,但是一开始没想明白越想越乱,最后看了下别人的实现,思路还是很清晰的,代码如下所示:

     1 /**
     2  * Definition for singly-linked list with a random pointer.
     3  * struct RandomListNode {
     4  *     int label;
     5  *     RandomListNode *next, *random;
     6  *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     7  * };
     8  */
     9 
    10 class Solution {
    11 public:
    12     RandomListNode *copyRandomList(RandomListNode *head) {
    13         unordered_map<RandomListNode *, RandomListNode *> m;
    14         RandomListNode helper1(0), * p1 = &helper1, helper2(0), *p2 = &helper2;
    15         p1->next = head;
    16         while(p1->next){
    17             p1 = p1->next;
    18             RandomListNode * tmpNode = new RandomListNode(p1->label);
    19             m[p1] = tmpNode;
    20             p2 = p2->next = tmpNode;
    21         }
    22         p1 = &helper1;
    23         while(p1->next){
    24             p1 = p1->next;
    25             if(p1->random){
    26                 m[p1]->random = m[p1->random];
    27             }
    28         }
    29         return helper2.next;
    30     }
    31 };
  • 相关阅读:
    Quick Sort 快速排序的原理及实现
    IAR_FOR_STM8开发之DEMO的建立
    跨域或者Internet访问Remoting[Remoting FAQ]
    2020 7 22 每日总结
    2020 7 23 每日总结
    2020 7 27 每日总结
    2020 7 20 每日总结
    2020 7 29 每日总结
    2020 7 21 每日总结
    2020 7 28 每日总结
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4993046.html
Copyright © 2011-2022 走看看