码迷,mamicode.com
首页 > 其他好文 > 详细

copy-list-with-random-pointer

时间:2019-05-10 14:36:35      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:==   init   struct   contain   代码   and   tno   solution   str   

原文地址: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

copy-list-with-random-pointer

标签:==   init   struct   contain   代码   and   tno   solution   str   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!