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 };
  • 相关阅读:
    NOIp2018集训test-10-17 (bike day3)
    NOIp2018集训test-10-16 (bike day2)
    django简介中
    django简介上
    bootstrap
    jQuery简介
    js完整篇
    css完结
    css三
    前端二与css开篇
  • 原文地址:https://www.cnblogs.com/tanghulu321/p/3390480.html
Copyright © 2011-2022 走看看