-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.go
126 lines (101 loc) · 1.92 KB
/
linked_list.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
118
119
120
121
122
123
124
125
126
package genericsds
import (
"errors"
)
type LinkedList[T any] struct {
head *linkedListNode[T]
tail *linkedListNode[T]
size int
}
func NewLinkedList[T any]() *LinkedList[T] {
return &LinkedList[T]{}
}
func NewListCollection[T any]() Collection[T] {
return NewLinkedList[T]()
}
var EmptyError = errors.New("List is empty")
type linkedListNode[T any] struct {
Datum T
Previous *linkedListNode[T]
Next *linkedListNode[T]
}
func (l *LinkedList[T]) Append(item T) {
if l.tail == nil {
l.tail = &linkedListNode[T]{
Datum: item,
Previous: nil,
Next: nil,
}
l.head = l.tail
} else {
l.tail.Next = &linkedListNode[T]{
Datum: item,
Previous: l.tail,
Next: nil,
}
l.tail = l.tail.Next
}
l.size++
}
func (l *LinkedList[T]) Add(item T) {
l.Append(item)
}
func (l *LinkedList[T]) Prepend(item T) {
if l.head == nil {
l.head = &linkedListNode[T]{
Datum: item,
Previous: nil,
Next: nil,
}
l.tail = l.head
} else {
l.head.Previous = &linkedListNode[T]{
Datum: item,
Previous: nil,
Next: l.head,
}
l.head = l.head.Previous
}
l.size++
}
func (l LinkedList[T]) ForEach(f func(item T)) {
for node := l.head; node != nil; node = node.Next {
f(node.Datum)
}
}
func (l LinkedList[T]) IsEmpty() bool {
return l.head == nil
}
func (l LinkedList[T]) Size() int {
return l.size
}
func (l *LinkedList[T]) RemoveLast() (T, error) {
if l.tail == nil {
var defaultValue T
return defaultValue, EmptyError
}
l.size--
toReturn := l.tail.Datum
l.tail = l.tail.Previous
if l.tail == nil {
l.head = nil
} else {
l.tail.Next = nil
}
return toReturn, nil
}
func (l *LinkedList[T]) RemoveFirst() (T, error) {
if l.head == nil {
var defaultValue T
return defaultValue, EmptyError
}
l.size--
toReturn := l.head.Datum
l.head = l.head.Next
if l.head == nil {
l.tail = nil
} else {
l.head.Previous = nil
}
return toReturn, nil
}