-
Notifications
You must be signed in to change notification settings - Fork 0
/
question28.go
80 lines (67 loc) · 1.14 KB
/
question28.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package chapter04
type Node struct {
value int
prev *Node
next *Node
child *Node
}
func flattenNode(node *Node) *Node {
n, _ := innerFlattenNode(node)
return n
}
func innerFlattenNode(node *Node) (next *Node, end *Node) {
iter, start := node, &Node{}
end = start
for iter != nil {
end.next = iter
iter.prev = end
end = end.next
if iter.child != nil {
s, e := innerFlattenNode(iter.child)
iter.child = nil
next := iter.next
end.next = s
s.prev = end
end = e
iter = next
continue
}
iter = iter.next
}
next = start.next
next.prev = nil
return next, end
}
type CreateNode struct {
value int
prev int
next int
child int
}
func createNode(nodes ...CreateNode) *Node {
var start *Node
idx := make(map[int]*Node)
for _, n := range nodes {
node := &Node{value: n.value}
idx[n.value] = node
if start == nil {
start = node
}
}
for _, n := range nodes {
node := idx[n.value]
if n.next > 0 {
next := idx[n.next]
node.next = next
}
if n.prev > 0 {
prev := idx[n.prev]
node.prev = prev
}
if n.child > 0 {
child := idx[n.child]
node.child = child
}
}
return start
}