-
Notifications
You must be signed in to change notification settings - Fork 0
/
sll.go
117 lines (93 loc) · 2.06 KB
/
sll.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
111
112
113
114
115
116
117
package sll
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"
)
// SLL provides the implementation of a singly-linked list
type SLL[TItem any] interface {
stack.Stack[TItem]
queue.Queue[TItem]
}
type node[TItem any] struct {
item TItem
next *node[TItem]
}
type sll[TItem any] struct {
first *node[TItem]
}
// New creates a new SLL
func New[TItem any]() SLL[TItem] {
return &sll[TItem]{nil}
}
// From creates a new SLL by concatenating the items
// of the given collection
func From[TItem any](c collection.Collection[TItem]) SLL[TItem] {
s := New[TItem]()
s.Concat(c)
return s
}
func (s *sll[TItem]) Count() int {
i := 0
current := s.first
for current != nil {
current = current.next
i++
}
return i
}
func (s *sll[TItem]) Concat(into iterator.IntoIterator[TItem]) collection.Collection[TItem] {
return s.Collect(into.Iter())
}
func (s *sll[TItem]) Collect(iter iterator.Iterator[TItem]) collection.Collection[TItem] {
iterator.ForEach(iter, func(item TItem) {
s.Append(item)
})
return s
}
func (s *sll[TItem]) Append(item TItem) collection.Collection[TItem] {
s.insertLast(item)
return s
}
func (s *sll[TItem]) Push(item TItem) {
s.insertFirst(item)
}
func (s *sll[TItem]) Pop() *TItem {
return s.removeFirst()
}
func (s *sll[TItem]) Peek() *TItem {
if s.first == nil {
return nil
}
return &s.first.item
}
func (s *sll[TItem]) Enqueue(item TItem) {
s.insertLast(item)
}
func (s *sll[TItem]) Dequeue() *TItem {
return s.removeFirst()
}
func (s *sll[TItem]) insertFirst(item TItem) {
tmp := s.first
s.first = &node[TItem]{item, tmp}
}
func (s *sll[TItem]) insertLast(item TItem) {
current := s.first
if current == nil {
s.first = &node[TItem]{item, nil}
return
}
for current.next != nil {
current = current.next
}
current.next = &node[TItem]{item, nil}
}
func (s *sll[TItem]) removeFirst() *TItem {
tmp := s.first
if tmp == nil {
return nil
}
s.first = s.first.next
return &tmp.item
}