Fork me on github

复杂链表的复制

递归处理链表问题,看起来很奇妙。

import java.util.HashMap;
import java.util.Map;

class Solution {
    Map<Node, Node> cachedNode = new HashMap<Node, Node>();

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        if (!cachedNode.containsKey(head)) {
            Node headNew = new Node(head.val);
            cachedNode.put(head, headNew);
            headNew.next = copyRandomList(head.next);
            headNew.random = copyRandomList(head.random);
        }
        return cachedNode.get(head);
    }
}
posted @ 2022-01-04 12:35  zjy4fun  阅读(25)  评论(0编辑  收藏  举报