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
  • 相关阅读:
    ZOJ4125 Sekiro
    ZOJ4118 Stones in the Bucket
    ZOJ4115 Wandering Robot
    ZOJ4113 Calandar
    【递归】N皇后问题 和 2n皇后问题 dfs
    7-18
    7_13
    二维前缀和
    64位整数乘法
    【分治】魔法石的诱惑
  • 原文地址:https://www.cnblogs.com/superzrx/p/3352745.html
Copyright © 2011-2022 走看看