This commit is contained in:
2026-06-21 16:31:54 +10:00
parent 35c362681e
commit c4cfce490e
3 changed files with 348 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
package top100liked
// https://leetcode.cn/problems/copy-list-with-random-pointer/?envType=study-plan-v2&envId=top-100-liked
type Node struct {
Val int
Next *Node
Random *Node
}
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
m := make(map[*Node]*Node)
cur := head
var first *Node
// 新旧节点映射
for cur != nil {
newNode := &Node{
Val: cur.Val,
Next: nil,
Random: nil,
}
if first == nil {
first = newNode
}
m[cur] = newNode
cur = cur.Next
}
cur = head
for cur != nil {
if cur.Next != nil {
m[cur].Next = m[cur.Next]
}
if cur.Random != nil {
m[cur].Random = m[cur.Random]
}
cur = cur.Next
}
return first
}