A linked list is given such this each node contains an additional random pointer which could point to all node in the list or null.
Return a deep copy of the list.
This is a list operation topic, requires copying a linked list, but each node of the list with a random pointer to a node point.
We first introduce a more straightforward algorithm, the idea is to copy a normal linked list, copy the copy of the node to do a hashmap, the old node as the key, the new node is value. The purpose of this is to use the hash table to connect the random pointers of the nodes to the second scan. This algorithm is relatively easy to think of, a total of two scans, so the time complexity is O (2*n) =o (n). Space requires a hash table to do the mapping of nodes, so the spatial complexity is also O (n). The code is as follows:
Public Randomlistnode copyrandomlist (Randomlistnode head) {if (head = = null) return head; hashmap<randomlistnode,randomlistnode> map = new hashmap<randomlistnode,randomlistnode> (); Randomlistnode newhead = new Randomlistnode (Head.label); Map.put (Head,newhead); Randomlistnode pre = Newhead; Randomlistnode node = head.next; while (node!=null) {Randomlistnode NewNode = new Randomlistnode (Node.label); Map.put (Node,newnode); Pre.next = NewNode; Pre = NewNode; node = Node.next; } node = head; Randomlistnode Copynode = Newhead; while (node!=null) {copynode.random = Map.get (node.random); Copynode = Copynode.next; node = Node.next; } return newhead; }
Copy List with Random pointer--leetcode