剑指 Offer 35. 复杂链表的复制

剑指 Offer 35. 复杂链表的复制

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

思路

在复制的时候用哈希表保存原链表的节点到新链表节点的对应关系,然后更新新链表中 random 的值

代码

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Node, Node> map = new HashMap<Node, Node>();
        Node copyHead = new Node(head.val);
        copyHead.random = head.random;
        Node copyCur = copyHead;
        Node cur = head;
        map.put(head, copyHead);
        while (cur.next != null) {
            Node copyNode = new Node(cur.next.val);
            copyNode.random = cur.next.random;
            map.put(cur.next, copyNode);
            copyCur.next = copyNode;
            cur = cur.next;
            copyCur = copyCur.next;
        }
        cur = copyHead;
        while (cur != null) {
            cur.random = map.get(cur.random);
            cur = cur.next;
        }
        return copyHead;
    }
}
posted @ 2022-04-14 16:29  沐灵_hh  阅读(13)  评论(0编辑  收藏  举报