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.
Ideas:
First, according to the normal order, to get a copy of the linked list, while using a hashmap to establish the corresponding relationship between the old and new nodes, and then add the random pointer, so that the random pointer point to the node is always a new node has been established, will not be null
/*** Definition for singly-linked list with a random pointer. * Class Randomlistnode {* int label; * Randomlist Node Next, Random; * Randomlistnode (int x) {This.label = x;}}; */ Public classSolution {/** * @paramhead:the head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */ PublicRandomlistnode copyrandomlist (Randomlistnode head) {//Write your code here if(Head = =NULL) return NULL; Randomlistnode Newhead=NewRandomlistnode (Head.label); Randomlistnode P1=Head.next; Randomlistnode P2=Newhead; HashMap<randomlistnode, randomlistnode> map =NewHashmap<randomlistnode, randomlistnode>(); Map.put (head, newhead); while(P1! =NULL) {P2.next=NewRandomlistnode (P1.label); P2=P2.next; Map.put (P1, p2); P1=P1.next; } p1=Head; P2=Newhead; while(P1! =NULL) {P2.random=Map.get (p1.random); P1=P1.next; P2=P2.next; } returnNewhead; }}
Lintcode-medium-copy List with Random Pointer