感觉一开始想到的办法还是比较笨
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
res := &Node{}
p1 := head
p2 := res
mp1 := make(map[*Node]int)
mp22 := make(map[int]*Node)
idx := 0
for p1!= nil {
p2.Val = p1.Val
if p1.Next != nil {
p2.Next = &Node{}
}
mp1[p1] = idx
mp22[idx] = p2
idx++
p1 = p1.Next
p2 = p2.Next
}
p1 = head
p2 = res
for p1 != nil {
if p1.Random != nil {
if idx, ok := mp1[p1.Random]; ok{
p2.Random = mp22[idx]
}
}
p1 = p1.Next
p2 = p2.Next
}
return res
}
用回溯方法做
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
var cache = make(map[*Node]*Node)
func copyRandomList(head *Node) *Node {
return deepCopy(head)
}
func deepCopy(head *Node) *Node {
if head == nil {
return nil
}
if node, ok := cache[head]; ok {
return node
}
newNode := &Node{}
newNode.Val = head.Val
cache[head] = newNode
newNode.Next = deepCopy(head.Next)
newNode.Random = deepCopy(head.Random)
return newNode
}
节点拆分法
/**
* Definition for a Node.
* type Node struct {
* Val int
* Next *Node
* Random *Node
* }
*/
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
for node := head; node != nil; node = node.Next.Next {
newNode := &Node{
Val: node.Val,
Next: node.Next,
}
node.Next = newNode
}
for node := head; node != nil; node = node.Next.Next {
if node.Random != nil {
newNode := node.Next
newNode.Random = node.Random.Next
}
}
res := head.Next
for node := head; node != nil; node = node.Next {
newNode := node.Next
next := newNode.Next
node.Next = next
if next != nil {
newNext := next.Next
newNode.Next = newNext
}
}
return res
}