-
Notifications
You must be signed in to change notification settings - Fork 0
/
dll.go
110 lines (90 loc) · 1.99 KB
/
dll.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package dll
import (
"github.com/bdreece/gollections/pkg/collection"
"github.com/bdreece/gollections/pkg/iterator"
"github.com/bdreece/gollections/pkg/queue"
"github.com/bdreece/gollections/pkg/stack"
)
// DLL provides the implementation of a doubly-linked list
// of nodes
type DLL[TItem any] interface {
stack.Stack[TItem]
queue.Queue[TItem]
}
type node[TItem any] struct {
item TItem
prev *node[TItem]
next *node[TItem]
}
type dll[TItem any] struct {
first *node[TItem]
last *node[TItem]
}
// New creates an empty DLL
func New[TItem any]() DLL[TItem] {
return &dll[TItem]{nil, nil}
}
// From creates a new DLL by concatenating the items
// of the given collection
func From[TItem any](c collection.Collection[TItem]) DLL[TItem] {
d := New[TItem]()
d.Concat(c)
return d
}
func (d *dll[TItem]) Count() int {
i := 0
current := d.first
for current != nil {
current = current.next
i++
}
return i
}
func (d *dll[TItem]) Concat(into iterator.IntoIterator[TItem]) collection.Collection[TItem] {
return d.Collect(into.Iter())
}
func (d *dll[TItem]) Collect(iter iterator.Iterator[TItem]) collection.Collection[TItem] {
iterator.ForEach(iter, func(item TItem) {
d.Append(item)
})
return d
}
func (d *dll[TItem]) Append(item TItem) collection.Collection[TItem] {
if d.first == nil {
d.first = &node[TItem]{item, nil, nil}
d.last = d.first
return d
}
d.last.next = &node[TItem]{item, d.last, nil}
d.last = d.last.next
return d
}
func (d *dll[TItem]) Push(item TItem) {
if d.first == nil {
d.first = &node[TItem]{item, nil, nil}
d.last = d.first
return
}
d.first.prev = &node[TItem]{item, nil, d.first}
d.first = d.first.prev
}
func (d *dll[TItem]) Pop() *TItem {
if d.first == nil {
return nil
}
val := d.first.item
d.first = d.first.next
return &val
}
func (d *dll[TItem]) Peek() *TItem {
if d.first == nil {
return nil
}
return &d.first.item
}
func (d *dll[TItem]) Enqueue(item TItem) {
d.Append(item)
}
func (d *dll[TItem]) Dequeue() *TItem {
return d.Pop()
}