/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/funccopyRandomList(head*Node)*Node{record:=make(map[*Node]*Node)vardfsfunc(root*Node)*Nodedfs=func(root*Node)*Node{ifnil==root{returnnil}ifret,ok:=record[root];ok{returnret}newNode:=&Node{Val:root.Val}record[root]=newNodenewNode.Next=dfs(root.Next)newNode.Random=dfs(root.Random)// record[root] = newNode 不能放在这里,会导致无限循环。
returnnewNode}returndfs(head)}
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/funccopyRandomList(head*Node)*Node{ifhead==nil{returnnil}fornode:=head;node!=nil;node=node.Next.Next{next:=node.Nextnode.Next=&Node{Val:node.Val,Next:next}}fornode:=head;node!=nil;node=node.Next.Next{ifnode.Random!=nil{node.Next.Random=node.Random.Next}}newHead:=head.Nextfornode:=head;node!=nil;node=node.Next{oldNext:=node.Next.NextifoldNext!=nil{node.Next.Next=oldNext.Next}node.Next=oldNext}returnnewHead}