算法-哈希表-复制带随机指针的链表

在这里插入图片描述

/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/

class Solution {
    public Node copyRandomList(Node head) {
        if(head == null) return null;
       

        Map<Node, Node> map = new HashMap<>();
        Node temp = head;
        //创建一个与当前节点对应的节点放进map里面去
        while(temp != null) {
            map.put(temp, new Node(temp.val));
            temp = temp.next;
        }

        Node target = map.get(head);
        Node p = target;
        while(head != null) {
            target.next = map.get(head.next);
            target.random = map.get(head.random);
            target = target.next;
            head = head.next;
        }

        return p;
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页