-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
75 lines (60 loc) · 1.24 KB
/
node.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
package go_directed_acyclic_graph
// Node represents a graph node.
type Node = interface{}
type nodeList struct {
nodes []Node
set map[Node]bool
}
func newNodeList() *nodeList {
return &nodeList{
nodes: make([]Node, 0),
set: make(map[Node]bool),
}
}
func (l *nodeList) Copy() *nodeList {
nodes := make([]Node, len(l.nodes))
copy(nodes, l.nodes)
set := make(map[Node]bool, len(nodes))
for _, node := range nodes {
set[node] = true
}
return &nodeList{
nodes: nodes,
set: set,
}
}
func (l *nodeList) Nodes() []Node {
return l.nodes
}
func (l *nodeList) Count() int {
return len(l.nodes)
}
func (l *nodeList) Exists(node Node) bool {
_, ok := l.set[node]
return ok
}
func (l *nodeList) Add(nodes ...Node) {
for _, node := range nodes {
if l.Exists(node) {
continue
}
l.nodes = append(l.nodes, node)
l.set[node] = true
}
}
func (l *nodeList) Remove(nodes ...Node) {
for i := len(l.nodes) - 1; i >= 0; i-- {
for j, node := range nodes {
if l.nodes[i] == node {
copy(l.nodes[i:], l.nodes[i+1:])
l.nodes[len(l.nodes)-1] = nil
l.nodes = l.nodes[:len(l.nodes)-1]
delete(l.set, node)
copy(nodes[j:], nodes[j+1:])
nodes[len(nodes)-1] = nil
nodes = nodes[:len(nodes)-1]
break
}
}
}
}