-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlist.go
46 lines (38 loc) · 810 Bytes
/
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
package gtl
type listElement[T any] struct {
v T
next *listElement[T]
}
// List defines a linked-list.
type List[T any] struct {
next *listElement[T]
}
// Add adds v to the front of the linked list.
func (lst *List[T]) Add(v T) {
e := listElement[T]{
v: v,
next: lst.next,
}
lst.next = &e
}
// PopFront returns the first listElement removing it from the linked list.
func (lst *List[T]) PopFront() (v T) {
if lst.next != nil {
v = lst.next.v
lst.next = lst.next.next
}
return
}
// Iter returns an iterator for the linked list.
func (lst *List[T]) Iter() Iterator[T] {
iter := &Iter[T, *listElement[T]]{
index: lst.next,
next: func(prev *listElement[T]) (*T, *listElement[T]) {
if prev == nil {
return nil, nil
}
return &prev.v, prev.next
},
}
return iter
}