Leetcode 138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

题意:深度复制一个带随机指针的链表。

思路:
开始是按照之前深度复制图的做法,利用深度优先搜索结合hashmap,但是遇到了栈溢出的bug,原因是这个链表的随机指针有可能会无限循环,比如A随机指向B,B随机指向A。下面是有bug的代码:

public RandomListNode copyRandomList(RandomListNode head) {

    Map map = new HashMap<>();

    return copyHelper(head, map);
}

private RandomListNode copyHelper(RandomListNode node, Map map) {
    if (node == null) {
        return null;
    }
    if (map.containsKey(node)) {
        return map.get(node);
    }

    RandomListNode copyNode = new RandomListNode(node.label);
    copyNode.next = copyHelper(node.next, map);
    copyNode.random = copyHelper(node.random, map);
    map.put(node, copyNode);

    return copyNode;
}

意识到bug是什么以后,就考虑如何避免random导致的死循环,想到了其实每个节点最多只有一个random指针,没必要把random加到搜索任务中。可以先遍历链表,建立映射关系,然后再遍历一次,把克隆节点连接起来。

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

    HashMap map = new HashMap<>();
    RandomListNode dummy = head;
    while (dummy != null) {
        RandomListNode copy = new RandomListNode(dummy.label);
        map.put(dummy, copy);
        dummy = dummy.next;
    }

    Queue q = new LinkedList<>();
    q.offer(head);
    while (!q.isEmpty()) {
        RandomListNode cur = q.poll();
        RandomListNode copy = map.get(cur);
        if (cur.next != null) {
            copy.next = map.get(cur.next);
            q.offer(cur.next);
        }
        if (cur.random != null) {
            copy.random = map.get(cur.random);
        }
    }

    return map.get(head);
}

你可能感兴趣的:(Leetcode 138. Copy List with Random Pointer)