noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

如何链表深拷贝

思路:用1个map保存旧链表和新链表节点的映射关系。

在复制旧链表节点node、node的next节点、node的random节点时,都去map去看下是否存在;

存在则直接返回,构建链表指针指向关系;不存在则new 一个节点出来。

 

 

class Solution {

    private Map<Node, Node> map = new HashMap<>();

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }

        Node pNode = new Node(-1);
        Node copHead = pNode;
        while (head != null) {
            Node curNode = buildCurNode(head);
            pNode.next = curNode;
            pNode = pNode.next;
            head = head.next;
        }

        return copHead.next;
        
    }

    private Node buildCurNode(Node head) {
        Node curNode = getNode(head);
        curNode.next = getNode(head.next);
        curNode.random = getNode(head.random);

        return curNode;
    }


    private Node getNode(Node head) {
        if (head == null) {
            return null;
        }

        Node node = null;
        // map中存在则返回旧节点指向的新节点;否则new 一个新的节点
        if (map.containsKey(head)) {
            node = map.get(head);
        } else {
            node = new Node(head.val);
            map.put(head, node);
        }
        return node;
    }

}

 

posted on 2021-03-09 00:23  noaman_wgs  阅读(79)  评论(0编辑  收藏  举报