Copy List with Random Pointer
Make a full copy of a linked list whose nodes also point to a random node, without a lookup map.
A linked list is a chain of nodes, where each node holds a value and a nextrandom
Given the first node, headnextrandomrandom
Example 1
Output: [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
Example 2
Output: [[1, 1], [2, 1]]
The Idea
Copying an ordinary linked list is a short walk: for each node, create a new node with the same value and hang it after the previous new node. The random
Take Example 2. It has two nodes, 1 and 2. The randomrandom
Now walk the list in order. When we create 1', the node 2' does not exist yet, so we cannot set 1'.random. Even later, once 2' exists, all that node 1 tells us is "my random is node 2". How do we get from an original node to its copy?
One way is to keep a table from each original node to its copy. A neater way needs no table: put each copy into the list itself, right after its original. Look at the picture below.
The top row, labelled "original list", is Example 2, with its random
Follow it one step further: the node after 2 is 2', exactly the node that 1'.random needs. That is the orange arrow, 1'.random = 1.random.next = 2'X.nextrandom
Solution Approach
Turning that idea into code means settling three things: how to reach each node's copy, where the copies' random
Reaching each node's copy
What is the simplest way to go from an original node to its copy? A HashMapnnextmap.get(n.next)randommap.get(n.random)
Weaving gives the same lookup with no map. Each copy is inserted between its original and the original's old nextnn.nextn = n.next.next
Setting the random pointers
Why not set randomnn.nextn.randomn.random.nextn.next.random = n.random.next
When n.randomrandom
Taking the lists apart
How do we end up with two separate lists? The caller still owns the original list, so it should look the same afterwards. A third pass walks the woven list once more. For each original nn.nextnext
Java Solution
The method copyRandomList
- First, if
is null, the list is empty and so is its copy: return null.head - Weave in the copies with a loop whose variable
visits each original node. For each one, createn withcopy , pointnew Node(n.val) at the node aftercopy.next , then pointn atn.next . The loop steps withcopy to jump over the copy it just made.n = n.next.next - A second loop visits the originals the same way. When
is not null, it setsn.random .n.next.random = n.random.next - Save the copy's first node,
, inhead.next . A third loop takes the copy of eachcopyHead , setsn to the node after the copy, and sets the copy'sn.next to the node after that, or null at the end. Sincenext is already restored, this loop steps withn.next .n = n.next - Return
.copyHead
The small NodemainbuildshowsharesNodes
The mainrandom
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
public class CopyListWithRandomPointer {
static class Node {
int val;
Node next;
Node random;
Node(int val) {
this.val = val;
}
}
public static Node copyRandomList(Node head) {
if (head == null) {
return null;
}
// 1. Put each copy right after its original: A -> A' -> B -> B' ...
for (Node n = head; n != null; n = n.next.next) {
Node copy = new Node(n.val);
copy.next = n.next;
n.next = copy;
}
// 2. A copy's random is the node right after the original's random.
for (Node n = head; n != null; n = n.next.next) {
if (n.random != null) {
n.next.random = n.random.next;
}
}
// 3. Split the two lists apart.
Node copyHead = head.next;
for (Node n = head; n != null; n = n.next) {
Node copy = n.next;
n.next = copy.next;
copy.next = (copy.next != null) ? copy.next.next : null;
}
return copyHead;
}
// Builds a list from pairs {value, index of random node}; -1 means null.
static Node build(int[][] pairs) {
List<Node> nodes = new ArrayList<>();
for (int[] p : pairs) {
nodes.add(new Node(p[0]));
}
for (int i = 0; i < pairs.length; i++) {
if (i + 1 < nodes.size()) {
nodes.get(i).next = nodes.get(i + 1);
}
if (pairs[i][1] >= 0) {
nodes.get(i).random = nodes.get(pairs[i][1]);
}
}
return nodes.isEmpty() ? null : nodes.get(0);
}
// Prints a list as [[value, index of random node], ...].
static String show(Node head) {
Map<Node, Integer> index = new IdentityHashMap<>();
int i = 0;
for (Node n = head; n != null; n = n.next) {
index.put(n, i++);
}
List<String> parts = new ArrayList<>();
for (Node n = head; n != null; n = n.next) {
Object r = (n.random == null) ? "null" : index.get(n.random);
parts.add("[" + n.val + ", " + r + "]");
}
return parts.toString();
}
// True if any node of the copy, or any random it points to, is a node of the original.
static boolean sharesNodes(Node original, Node copy) {
Map<Node, Boolean> seen = new IdentityHashMap<>();
for (Node n = original; n != null; n = n.next) {
seen.put(n, true);
}
for (Node n = copy; n != null; n = n.next) {
if (seen.containsKey(n) || (n.random != null && seen.containsKey(n.random))) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Node head = build(new int[][] {{7, -1}, {13, 0}, {11, 4}, {10, 2}, {1, 0}});
Node copy = copyRandomList(head);
System.out.println("copy: " + show(copy));
System.out.println("original after: " + show(head));
System.out.println("shares nodes: " + sharesNodes(head, copy));
Node two = build(new int[][] {{1, 1}, {2, 1}});
System.out.println("copy: " + show(copyRandomList(two)));
Node self = build(new int[][] {{5, 0}});
Node selfCopy = copyRandomList(self);
System.out.println("copy: " + show(selfCopy));
System.out.println("random is self: " + (selfCopy.random == selfCopy));
System.out.println("empty list: " + copyRandomList(null));
}
}
Running it prints:
copy: [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
original after: [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]
shares nodes: false
copy: [[1, 1], [2, 1]]
copy: [[5, 0]]
random is self: true
empty list: null
The copy of Example 1 prints as [[7, null], [13, 0], [11, 4], [10, 2], [1, 0]]original afternextshares nodesrandom
Look at random is self: truen.random.nextn.next
The second loop is easy to write as n.next.random = n.random.next[[7, null], [13, null], [11, null], [10, null], [1, null]]shares nodesrandomshow
Complexity
The method walks the list three times and creates one new node for each original node.
- Time: O(n), for a list of n nodes: each of the three loops visits every original node once, and does a fixed number of pointer changes there, even though the woven list briefly has 2n nodes.
- Space: O(1) besides the copy. The n new nodes are the answer itself. Apart from them, the method keeps only
,n andcopy , where the table version would need a map entry for every node.copyHead
A map from each original to its copy is also how a graph is copied in