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
  • 相关阅读:
    洛谷 P1284 三角形牧场WD
    luogu P3817 小A的糖果
    P3374 【模板】树状数组 1
    线程与threading模块
    socketserver模块
    python 粘包问题及解决方法
    python 网络编程
    类的进阶四 反射和内置方法
    python hashlib模块 logging模块 subprocess模块
    类的进阶三
  • 原文地址:https://www.cnblogs.com/superzrx/p/3352745.html
Copyright © 2011-2022 走看看