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

Copy List with Random Pointer (Hash表)

时间:2015-01-24 17:10:49      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        if(head==NULL) return head;
        map<RandomListNode*,int> hash;
        map<int,RandomListNode*> copyHash;

        RandomListNode* copyHead=new RandomListNode(head->label);
        RandomListNode* p=head;
        RandomListNode* q=copyHead;
        int index=0;
        hash[p]=index;
        copyHash[index]=q;
        ++index;
        p=p->next;

        //复制整个链表
        while(p!=NULL){
            RandomListNode* newNode=new RandomListNode(p->label);
            q->next=newNode;
            q=q->next;
            hash[p]=index;
            copyHash[index]=q;
            ++index;
            p=p->next;
        }
        //最后的NULL节点也要加进去
        hash[NULL]=index;
        copyHash[index]=NULL;
        
        //复制random指针
        int i=0;
        RandomListNode* r=head;
        while (i<hash.size()&&r!=NULL)
        {
            copyHash[i]->random=copyHash[hash[r->random]];
            ++i;
            r=r->next;
        }
        return copyHead;
    }
};

 

Copy List with Random Pointer (Hash表)

标签:

原文地址:http://www.cnblogs.com/fightformylife/p/4246087.html

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