• Copy List with Random Pointer (Hash表)


    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;
        }
    };
  • 相关阅读:
    发送邮件
    php防止表单重复提交
    mysql 优化之注意
    mysqldump
    项目中下拉框链接问题
    css在IE和Firefox下的兼容性
    利用curl并发来提高页面访问速度
    修改linux下mysql目录权限
    ajax跨域
    wireshark抓包
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4246087.html
Copyright © 2020-2023  润新知