Copy List with Random Pointer(0138/Medium)
Copy a postings list
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.
public class PNode<E> {
public E data;
public PNode<E> next;
PNode<E> jump;
public PNode(E data,PNode<E> next, PNode<E> jump) {
this.data = data;
this.next = next;
this.jump = jump;
}
public PNode(E data,PNode<E> next) {
this.data = data;
this.next = next;
this.jump = null;
}
}
public static PNode<Integer> copyPostingsList(PNode<Integer> L) {
if (L == null) {
return null;
}
// Stage 1: Makes a copy of the original list without assigning the jump
// field, and creates the mapping for each node in the original
// list to the copied list.
PNode<Integer> iter = L;
while (iter != null) {
PNode<Integer> newNode = new PNode<>(iter.data, iter.next, null);
iter.next = newNode;
iter = newNode.next;
}
// Stage 2: Assigns the jump field in the copied list.
iter = L;
while (iter != null) {
if (iter.jump != null) {
iter.next.jump = iter.jump.next;
}
iter = iter.next.next;
}
// Stage 3: Reverts the original list, and assigns the next field of
// the copied list.
iter = L;
PNode<Integer> newListHead = iter.next;
while (iter != null) {
PNode<Integer> newNode = iter.next;
iter.next = newNode.next;
if(newNode.next!=null)
newNode.next = newNode.next.next;
iter = iter.next;
}
return newListHead;
}