/*// Definition for a Node.class Node {public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; }};*/classSolution{public:Node*copyRandomList(Node*head){Node*dummy=newNode(0);Node*tail=dummy;unordered_map<Node*,Node*>d;for(Node*cur=head;cur;cur=cur->next){Node*node=newNode(cur->val);tail->next=node;tail=node;d[cur]=node;}for(Node*cur=head;cur;cur=cur->next){d[cur]->random=cur->random?d[cur->random]:nullptr;}returndummy->next;}};
/** * Definition for a Node. * type Node struct { * Val int * Next *Node * Random *Node * } */funccopyRandomList(head*Node)*Node{dummy:=&Node{}tail:=dummyd:=map[*Node]*Node{}forcur:=head;cur!=nil;cur=cur.Next{node:=&Node{Val:cur.Val}d[cur]=nodetail.Next=nodetail=node}forcur:=head;cur!=nil;cur=cur.Next{ifcur.Random!=nil{d[cur].Random=d[cur.Random]}}returndummy.Next}
/*// Definition for a Node.public class Node { public int val; public Node next; public Node random; public Node(int _val) { val = _val; next = null; random = null; }}*/publicclassSolution{publicNodeCopyRandomList(Nodehead){Dictionary<Node,Node>d=newDictionary<Node,Node>();Nodedummy=newNode(0);Nodetail=dummy;for(Nodecur=head;cur!=null;cur=cur.next){Nodenode=newNode(cur.val);tail.next=node;tail=node;d[cur]=node;}for(Nodecur=head;cur!=null;cur=cur.next){if(cur.random!=null){d[cur].random=d[cur.random];}}returndummy.next;}}
/*// Definition for a Node.class Node {public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; }};*/classSolution{public:Node*copyRandomList(Node*head){if(!head){returnnullptr;}Node*cur=head;while(cur!=nullptr){Node*node=newNode(cur->val);node->next=cur->next;cur->next=node;cur=node->next;}cur=head;while(cur!=nullptr){cur->next->random=cur->random==nullptr?nullptr:cur->random->next;cur=cur->next->next;}cur=head;Node*ans=head->next;while(cur->next!=nullptr){Node*node=cur->next;cur->next=node->next;cur=node;}returnans;}};
/** * Definition for a Node. * type Node struct { * Val int * Next *Node * Random *Node * } */funccopyRandomList(head*Node)*Node{ifhead==nil{returnnil}forcur:=head;cur!=nil;{node:=&Node{cur.Val,cur.Next,nil}cur.Next=nodecur=node.Next}forcur:=head;cur!=nil;cur=cur.Next.Next{ifcur.Random!=nil{cur.Next.Random=cur.Random.Next}}ans:=head.Nextforcur:=head;cur.Next!=nil;{node:=cur.Nextcur.Next=node.Nextcur=node}returnans}
/*// Definition for a Node.public class Node { public int val; public Node next; public Node random; public Node(int _val) { val = _val; next = null; random = null; }}*/publicclassSolution{publicNodeCopyRandomList(Nodehead){if(head==null){returnnull;}Nodecur=head;while(cur!=null){Nodenode=newNode(cur.val);node.next=cur.next;cur.next=node;cur=node.next;}cur=head;while(cur!=null){cur.next.random=cur.random==null?null:cur.random.next;cur=cur.next.next;}cur=head;Nodeans=head.next;while(cur.next!=null){Nodenode=cur.next;cur.next=node.next;cur=node;}returnans;}}