一起来刷算法题

copy-list-with-random-pointer

2019-05-10  本文已影响0人  cherryleechen

时间限制: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

上一篇下一篇

猜你喜欢

热点阅读