A special list node class is described below:
public class node{
public int value;
Public Node Next;
Public Node Rand;
public Node (int data) {
This.value = Data
}
}
The rand pointer is a new pointer in the node class, which may point to any node in the linked list, or it may point to null
The general solution is introduced first:
Using a hash table
First, the linked list is traversed from left to right, and the corresponding replica node is copied for each node
Key 1 value 1 '
PackageTT;ImportJava.util.HashMap; Public classTest95 { Public classnode{ Public intvalue; PublicNode Next; PublicNode Rand; PublicNode (intdata) { This. value=data; } } Publicnode CopyListWithRand1 (node head) {HashMap<node, node> map=NewHashmap<node, node>(); Node cur=Head; while(cur! =NULL) {map.put (cur,NewNode (Cur.value)); Cur=Cur.next; } cur=Head; while(cur!=NULL) {map.get (cur). Next=Map.get (Cur.next); Map.get (cur). Rand=Map.get (Cur.rand); Cur=Cur.next; } returnMap.get (head); } }
The algorithm summarizes a list of nodes that contain random pointers