-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-list.go
More file actions
94 lines (82 loc) · 1.97 KB
/
node-list.go
File metadata and controls
94 lines (82 loc) · 1.97 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package GoHtml
import (
"container/list"
"iter"
)
//NodeList can store nodes by appended order and can iterate over the node list by invoking IterNodeList method.
type NodeList struct {
list *list.List
currentEl *list.Element
}
// New returns an initialized node list.
func NewNodeList() NodeList {
return NodeList{
list: list.New(),
currentEl: nil,
}
}
// Len returns the number of node in the list. The complexity is O(1).
func (nl *NodeList) Len() int {
return nl.list.Len()
}
// Next advanced to the next node and returns that node.
func (nl *NodeList) Next() *Node {
if nl.list.Len() == 0 {
return nil
}else if nl.currentEl == nil && nl.list.Len() > 0{
nl.currentEl = nl.list.Front()
} else {
if nl.currentEl.Next() == nil{
return nil
}
nl.currentEl = nl.currentEl.Next()
}
return nl.currentEl.Value.(*Node)
}
// Previous advanced to the previous node and return that node.
func (nl *NodeList) Previous() *Node {
if nl.currentEl == nil {
nl.currentEl = nl.list.Front()
} else {
if nl.currentEl.Prev() == nil {
return nil
}
nl.currentEl = nl.currentEl.Prev()
}
return nl.currentEl.Value.(*Node)
}
// Back returns the last node of list or nil if the list is empty.
func (nl *NodeList) Back() *Node {
if nl.list.Back() == nil {
return nil
}
return nl.list.Back().Value.(*Node)
}
// Front returns the first node of list or nil if the list is empty.
func (nl *NodeList) Front() *Node {
if nl.list.Front() == nil {
return nil
}
return nl.list.Front().Value.(*Node)
}
// Append append a node to the back of the list.
func (nl *NodeList) Append(node *Node) {
if node == nil{
return
}
nl.list.PushBack(node)
}
// IterNodeList returns a iterator over the node list.
func (nl *NodeList) IterNodeList() iter.Seq[*Node] {
return func(yield func(*Node) bool) {
nodeList := NewNodeList()
nodeList.list = nl.list
nextNode := nodeList.Next()
for nextNode != nil{
if !yield(nextNode) {
return
}
nextNode = nodeList.Next()
}
}
}