zoukankan      html  css  js  c++  java
  • 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.

    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            map<RandomListNode*,RandomListNode*> ptrs;
            RandomListNode* ret=NULL;
            RandomListNode* ptr=NULL,*ptr2=NULL,*ptr3=NULL;
            if(head!=NULL){
                ret=new RandomListNode(head->label);
                if(head->random!=NULL){
                    ret->random=new RandomListNode(head->random->label);
                    ptrs[head->random]=ret->random;
                }
                ptrs[head]=ret;
                head=head->next;
                ptr=ret;
            }
            else return NULL;
            while(head!=NULL){
                if(ptrs.find(head)==ptrs.end()){
                    ptr2=new RandomListNode(head->label);
                    ptrs[head]=ptr2;
                    ptr->next=ptr2;
                }
                else{
                    ptr2=ptrs[head];
                    ptr->next=ptr2;
                }
                if(head->random!=NULL){
                    if(ptrs.find(head->random)==ptrs.end()){
                        ptr2->random=new RandomListNode(head->random->label);
                        ptrs[head->random]=ptr2->random;
                    }
                    else{
                        ptr2->random=ptrs[head->random];
                    }
                }
                head=head->next;
                ptr=ptr2;
            }
            return ret;
        }
    };
    View Code
  • 相关阅读:
    树链剖分求LCA
    洛谷P1019 单词接龙
    洛谷P1441 砝码称重
    洛谷P2347 砝码称重
    洛谷P1164 小A点菜
    洛谷P2202 [USACO13JAN]方块重叠Square Overlap
    黑客与画家 第四章
    黑客与画家 第十二章
    记录最近一段的体会
    11.5最小生成树(Minimum Spanning Trees)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3352745.html
Copyright © 2011-2022 走看看