-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob0138.go
52 lines (43 loc) · 881 Bytes
/
prob0138.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package prob0138
type Node struct {
Val int
Next *Node
Random *Node
}
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
newNodeList := make([]*Node, 0)
nodeMap := make(map[*Node]int)
// copy node
preHead := &Node{Next: head}
cursor := preHead
index := 0
for cursor.Next != nil {
cursor = cursor.Next
newNodeList = append(newNodeList, copyNode(cursor))
nodeMap[cursor] = index
index += 1
}
// reorganization
newPreHead := &Node{Next: newNodeList[0]}
cursor = newPreHead
for cursor.Next != nil {
cursor = cursor.Next
if cursor.Next != nil {
cursor.Next = newNodeList[nodeMap[cursor.Next]]
}
if cursor.Random != nil {
cursor.Random = newNodeList[nodeMap[cursor.Random]]
}
}
return newPreHead.Next
}
func copyNode(n *Node) *Node {
return &Node{
Val: n.Val,
Next: n.Next,
Random: n.Random,
}
}