其他分享
首页 > 其他分享> > 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);
        }
    }

 

标签:Node,map,clone,List,next,oldNode,newNode,138,Pointer
来源: https://www.cnblogs.com/feiflytech/p/15800374.html