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
  • 相关阅读:
    浅谈分层图最短路问题
    [Luogu P2574]XOR的艺术
    luogu P2419 [USACO08JAN]牛大赛Cow Contest
    luogu P1119 灾后重建
    [国家集训队]跳跳棋
    洛谷P4147 玉蟾宫
    [ZJOI2007]棋盘制作
    树状数组模版
    Nearest Common Ancestor
    P1260 工程规划
  • 原文地址:https://www.cnblogs.com/superzrx/p/3352745.html
Copyright © 2011-2022 走看看