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 };
  • 相关阅读:
    http uri唯一标识
    http协议
    python模块 sys
    file 文件的操作
    库的介绍及使用
    python os模块
    python的序列化与反序列化
    python 字典的定义以及方法
    python字符串的常用方法
    在Windows下使用adb logcat grep
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4993046.html
Copyright © 2011-2022 走看看