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

在这里插入图片描述

/*
// 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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45100361/article/details/113087228