標籤: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