zoukankan      html  css  js  c++  java
  • Copy list with random pointer

     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         
    13         if (head == NULL) return NULL;
    14         RandomListNode *result = new RandomListNode(head->label), *next, *random;
    15         
    16         unordered_map<RandomListNode*, RandomListNode*> dict;
    17         dict[head] = result;
    18         
    19         while (head){
    20             
    21             if (head->random){
    22                 
    23                 if (dict[head->random]) dict[head]->random = dict[head->random];
    24                 else{
    25                     dict[head->random] = new RandomListNode(head->random->label);
    26                     dict[head]->random = dict[head->random];
    27                 }
    28             }
    29             
    30             if (head->next){
    31                 
    32                 if (dict[head->next]) dict[head]->next = dict[head->next];
    33                 else{
    34                     dict[head->next] = new RandomListNode(head->next->label);
    35                     dict[head]->next = dict[head->next];
    36                 }
    37             }
    38             head = head->next;
    39         }
    40         return result;
    41     }
    42 };
  • 相关阅读:
    数据库编程总结
    Excel文件操作方式比较
    大数据导入Excel
    导出Excel
    duilib库分析: 消息流程分析
    ucosII移植
    Log Parser Studio 分析 IIS 日志
    google 搜索关键字技巧
    未知的反物质世界的瞎想
    Scratch 简单的小游戏 --- 碰碰球
  • 原文地址:https://www.cnblogs.com/tanghulu321/p/3390480.html
Copyright © 2011-2022 走看看