LeetCode: Copy List with Random Pointer

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   strong   for   div   代碼   

LeetCode: 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.

地址:https://oj.leetcode.com/problems/copy-list-with-random-pointer/

演算法:將已經複製的節點儲存在map裡面。如果當前遍曆到的節點在map裡,則直接取出來;若不再map裡則複製節點,並將節點儲存在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 class Solution {10 public:11     RandomListNode *copyRandomList(RandomListNode *head) {12         RandomListNode *p = head;13         RandomListNode *new_head = NULL;14         map<int, RandomListNode*> hash_table;15         RandomListNode *new_p;16         int label, r_label;17         while(p){18             label = p->label;19             if(hash_table.find(label) == hash_table.end()){20                 RandomListNode * temp_p = new RandomListNode(label);21                 hash_table[label] = temp_p;22             }23             if(!new_head){24                 new_head = hash_table[label];25                 new_p = new_head;26             }else{27                 new_p->next = hash_table[label];28                 new_p = new_p->next;29             }30             if(p->random){31                 r_label = p->random->label;32                 if(hash_table.find(r_label) == hash_table.end()){33                     RandomListNode *temp_p = new RandomListNode(r_label);34                     hash_table[r_label] = temp_p;35                 }36                 new_p->random = hash_table[r_label];37             }38             p = p->next;39         }40         return new_head;41     }42 };

 

LeetCode: Copy List with Random Pointer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.