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.
     
    Solution: Solution 1 uses constant extra space.
     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 class Solution {
    10 public:
    11     RandomListNode *copyRandomList(RandomListNode *head) {
    12         if (!head) return NULL;
    13         unordered_map<RandomListNode *, RandomListNode *> map;
    14         RandomListNode dummy(0), *curNew = &dummy, *cur = head;
    15         while (cur) 
    16         {
    17             if (map.find(cur) == map.end())
    18                 map[cur] = new RandomListNode(cur->label);
    19             if (cur->random && map.find(cur->random) == map.end())
    20                 map[cur->random] = new RandomListNode(cur->random->label);
    21             curNew->next = map[cur];
    22             curNew = curNew->next;
    23             curNew->random = map[cur->random];
    24             cur = cur->next;
    25         }
    26         return dummy.next;
    27     }
    28 };
  • 相关阅读:
    多进程2
    并发编程
    粘包
    socket
    网络编程
    异常与网络编程
    面向对象高级
    多态
    面向对象2
    SQL数据库约束行为---防止数据乱填(即数据规范化)
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682336.html
Copyright © 2011-2022 走看看