leetcode - 138. Copy List with Random Pointer

网上有另一种解法,是把新的节点放在旧的节点之后,但要多一次遍历,应该还是用hash比较简洁快速。
在这里插入图片描述

class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node* ph=new Node(-1,NULL,NULL),*p1=ph,*p2=head;
        unordered_map<Node*,Node*> hash;
        while(head)
        {
            p1->next=new Node(head->val,NULL,NULL);
            p1=p1->next;
            hash[head]=p1;
            head=head->next;
        }
        p1=ph->next;
        while(p2)
        {
            if(p2->random)
            {
                p1->random=hash[p2->random];
            }
            p2=p2->next;
            p1=p1->next;
        }
        return ph->next;
    }
    
};

猜你喜欢

转载自blog.csdn.net/weixin_41938758/article/details/88947820