-
Notifications
You must be signed in to change notification settings - Fork 8
/
stack.go
56 lines (45 loc) · 890 Bytes
/
stack.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
package gtree
import (
"container/list"
"errors"
)
var errNilStack = errors.New("nil stack")
type stack struct {
nodes *list.List
}
func newStack() *stack {
return &stack{nodes: list.New()}
}
func (s *stack) push(n *Node) *stack {
s.nodes.PushBack(n)
return s
}
func (s *stack) pop() *Node {
tmp := s.nodes.Back()
if tmp == nil {
return nil
}
return s.nodes.Remove(tmp).(*Node)
}
func (s *stack) size() int {
return s.nodes.Len()
}
// depth-first search
func (s *stack) dfs(current *Node) {
size := s.size()
for i := 0; i < size; i++ {
parent := s.pop()
if !current.isDirectlyUnder(parent) {
continue
}
// for same name on the same hierarchy
if child := parent.findChildByText(current.name); child != nil {
s.push(parent).push(child)
return
}
parent.addChild(current)
current.setParent(parent)
s.push(parent).push(current)
return
}
}