-
Notifications
You must be signed in to change notification settings - Fork 0
/
doubly_linked_list.go
67 lines (53 loc) · 946 Bytes
/
doubly_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
package ratelimiter
import "errors"
var (
ErrListIsEmpty = errors.New("the list is empty")
)
type item struct {
next *item
prev *item
value interface{}
}
type DoublyLinkedListInterface interface {
PushBack(v interface{})
PopFront() (interface{}, error)
IsEmpty() bool
}
type DoublyLinkedList struct {
head *item
tail *item
}
func (l *DoublyLinkedList) PushBack(v interface{}) {
if l.tail == nil {
l.tail = &item{
next: nil,
prev: nil,
value: v,
}
l.head = l.tail
} else {
i := &item{
next: nil,
prev: l.tail,
value: v,
}
l.tail.next = i
l.tail = i
}
}
func (l *DoublyLinkedList) PopFront() (interface{}, error) {
if l.IsEmpty() {
return nil, ErrListIsEmpty
}
currentHead := l.head
l.head = currentHead.next
if l.head == nil {
l.tail = nil
} else {
l.head.prev = nil
}
return currentHead.value, nil
}
func (l *DoublyLinkedList) IsEmpty() bool {
return l.head == nil
}