LeetCode 138. Copy List with Random Pointer

Tech In Pieces發表於2020-12-09

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.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  1. val: an integer representing Node.val
  2. random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.

idea:
it’s a deep copy related problem instead of the random related question.

class Solution {
    //this hashmap use old nodes as keys and new Node(node.val) as the deep copy
    HashMap<Node, Node> visited = new HashMap<Node, Node>(); 
    private Node getCloneNode(Node node) {
        if (node != null) {
            if (this.visited.containsKey(node)) { //if we have this key
                return this.visited.get(node); //return it's corresponding node
            } else {
                this.visited.put(node, new Node(node.val)); //if we dont have, then put it in that
                return this.visited.get(node); //return the value
            }
        }
        return null;
    }
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        
        Node oldNode = head;
        Node newNode = new Node(oldNode.val);
        this.visited.put(oldNode, newNode);
        
        while (oldNode != null) {
            newNode.random = this.getCloneNode(oldNode.random); //newNode.random is a clone from oldNode.random
            newNode.next = this.getCloneNode(oldNode.next);
            
            oldNode = oldNode.next;
            newNode = newNode.next;
        }
        return this.visited.get(head); //
    }
}

相關文章