当前位置:   article > 正文

Leetcode138(力扣138):复制带随机指针的链表

力扣138

在这里插入图片描述
思路:遍历一次,先创建好所有节点,将节点和原链表放入哈希表 ,然后再次遍历,将所有结点对应连接

class Solution
{
public:
    Node* copyRandomList(Node* head) 
    {
        if(!head) return head;
        Node* cur=head;
        unordered_map<Node*,Node*> keep;
        while(cur)
        {
            Node* copy=new Node(cur->val);
            keep[cur]=copy;
            cur=cur->next;
        }
        cur=head;
        while(cur)
        {
            keep[cur]->next=keep[cur->next];
            keep[cur]->random=keep[cur->random];
            cur=cur->next;
        }
        return keep[head];
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/737855
推荐阅读
相关标签
  

闽ICP备14008679号