138. Copy List with Random Pointer(138. Copy List with Random Pointer)

这道题咋看挺复杂,又要clone node还要clone random link,但其实只要用一个HashMap就可以轻松解决,以下是我的算法,先clone node和node的next link,然后clone node的random link,时间复杂度O(n):

    public Node copyRandomList(Node head) {
        if (head == null)
            return null;
        Map<Node, Node> map = new HashMap<>();
        Node res = new Node(head.val);
        clone(head, res, map);
        randomLink(head, res, map);
        return res;
    }

    private void clone(Node oldNode, Node newNode, Map<Node, Node> map) {
        map.put(oldNode, newNode);
        if (oldNode.next != null) {
            newNode.next = new Node(oldNode.next.val);
            clone(oldNode.next, newNode.next, map);
        }
    }

    private void randomLink(Node oldNode, Node newNode, Map<Node, Node> map) {
        if (oldNode.random != null) {
            newNode.random = map.get(oldNode.random);
        }
        if (oldNode.next != null) {
            randomLink(oldNode.next, newNode.next, map);
        }
    }
————————

This problem is very complicated at first. It requires both clone node and clone random link, but in fact, it can be easily solved by using a HashMap. The following is my algorithm. First clone node and next link of node, and then random link of clone node. The time complexity is O (n):

    public Node copyRandomList(Node head) {
        if (head == null)
            return null;
        Map<Node, Node> map = new HashMap<>();
        Node res = new Node(head.val);
        clone(head, res, map);
        randomLink(head, res, map);
        return res;
    }

    private void clone(Node oldNode, Node newNode, Map<Node, Node> map) {
        map.put(oldNode, newNode);
        if (oldNode.next != null) {
            newNode.next = new Node(oldNode.next.val);
            clone(oldNode.next, newNode.next, map);
        }
    }

    private void randomLink(Node oldNode, Node newNode, Map<Node, Node> map) {
        if (oldNode.random != null) {
            newNode.random = map.get(oldNode.random);
        }
        if (oldNode.next != null) {
            randomLink(oldNode.next, newNode.next, map);
        }
    }