• LeetCode: Copy List with Random Pointer


    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 };

     

  • 相关阅读:
    HDOJ2553 N皇后问题
    NYOJ284 坦克大战 BFS/优先队列
    NYOJ14 会场安排问题 贪心
    POJ1664 放苹果
    NYOJ119 士兵杀敌(三) RMQ
    POJ3264 Balanced Lineup RMQ/线段树
    POJ1127 Jack Straws
    HDOJ1128 Self Numbers
    水晶报表CrystalReports很强大也很简单!
    PetShop项目学习笔记(三)
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_copy_list_with_random_pointer.html
Copyright © 2020-2023  润新知