138. 复制带随机指针的链表

image.png

image.png

Map

主要需要建立next 和random 随机节点的关联

  1. package main
  2. import "unsafe"
  3. type Node struct {
  4. Val int
  5. Next *Node
  6. Random *Node
  7. }
  8. func copyRandomList(head *Node) *Node {
  9. curr := head
  10. m := make(map[uintptr]*Node)
  11. for curr!=nil{
  12. node :=&Node{Val:curr.Val}
  13. m[uintptr(unsafe.Pointer(curr))]=node
  14. curr = curr.Next
  15. }
  16. curr = head
  17. for curr!=nil{
  18. node := m[uintptr(unsafe.Pointer(curr))]
  19. node.Next = m[uintptr(unsafe.Pointer(curr.Next))]
  20. node.Random =m[uintptr(unsafe.Pointer(curr.Random))]
  21. curr = curr.Next
  22. }
  23. return m[uintptr(unsafe.Pointer(head))]
  24. }
  25. func main() {
  26. }

image.png