copy-list-with-random-pointer

原文地址:https://www.jianshu.com/p/e8481d454076

时间限制:1秒 空间限制:32768K

题目描述

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.

我的代码

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(head==nullptr)
            return nullptr;
        map<RandomListNode*,RandomListNode*> m;
        RandomListNode* cur=head;
        RandomListNode* curClone=new RandomListNode(cur->label);
        m[cur]=curClone;
        RandomListNode* cloneHead=curClone;
        while(cur){
            if(cur->next){
                RandomListNode* tmp=new RandomListNode(cur->next->label);
                curClone->next=tmp;
            }
            else
                curClone->next=nullptr;
            cur=cur->next;
            curClone=curClone->next;
            m[cur]=curClone;
        }
        cur=head;curClone=cloneHead;
        while(cur){
            curClone->random=m[cur->random];
            cur=cur->next;
            curClone=curClone->next;
        }
        return cloneHead;
    }
};

运行时间:30ms
占用内存:1400k

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(head==nullptr)
            return nullptr;
        RandomListNode* cur=head;
        RandomListNode* curCopy=nullptr;
        while(cur){
            curCopy=new RandomListNode(cur->label);
            curCopy->next=cur->next;
            cur->next=curCopy;
            cur=curCopy->next;
        }
        cur=head;curCopy=head->next;
        while(cur){
            if(cur->random)
                curCopy->random=cur->random->next;
            cur=curCopy->next;
            curCopy=cur->next;
        }
        RandomListNode* cloneHead=head->next;
        //拆
        cur=head;
        while(cur->next){
            curCopy=cur->next;
            cur->next=cur->next->next;
            cur=curCopy;
        }
        return cloneHead;
    }
};

运行时间:19ms
占用内存:1388k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10844131.html