首页 > 其他 > 详细

Copy List with Random Pointer (Hash表)

时间:2015-01-24 17:07:36      阅读:268      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!