Copy List with Random Pointer

Question (LC.138)

Given a speical linked list (each node contains a random pointer), make a deep copy of the list.

private class RandomListNode {
    int value;
    RandomListNode next;
    RandomListNode random;
    public RandomListNode(int value) {
        this.value = value;
    }
}

Example

For data structure questions, drawing out is normally a good idea since just thinking won't be very helpful.

Analysis

There are 4 types of edges - backward, forward, self, and null. Forward edges are troublesome because we don't know how far it will take us and thereby whether creating a new node.

BFS Approach

We can think of this question as a simplifying version of clone graph.

Step 1 and Step 2 can be combined because next guarantees us the next node.

BFS Code

Even/Odd Approach

Last updated