This repository has been archived by the owner on Jun 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deque.go
91 lines (82 loc) · 1.41 KB
/
deque.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
package deque
import (
"errors"
)
type node[T interface{}] struct {
val T
prev *node[T]
next *node[T]
}
type Deque[T interface{}] struct {
head *node[T]
tail *node[T]
size uint
}
func (d *Deque[T]) AddFirst(val T) {
newNode := new(node[T])
newNode.val = val
if d.size == 0 {
d.head = newNode
d.tail = newNode
} else {
newNode.next = d.head
d.head.prev = newNode
d.head = newNode
}
d.size++
}
func (d *Deque[T]) RemoveFirst() (T, error) {
if d.size == 0 {
return *new(T), errors.New("empty deque")
}
val := d.head.val
if d.size == 1 {
d.head = nil
d.tail = nil
} else {
d.head = d.head.next
d.head.prev = nil
}
d.size--
return val, nil
}
func (d *Deque[T]) GetFirst() (T, error) {
if d.size == 0 {
return *new(T), errors.New("empty deque")
}
return d.head.val, nil
}
func (d *Deque[T]) AddLast(val T) {
newNode := new(node[T])
newNode.val = val
if d.size == 0 {
d.tail = newNode
d.head = newNode
} else {
newNode.prev = d.tail
d.tail.next = newNode
d.tail = newNode
}
d.size++
}
func (d *Deque[T]) RemoveLast() (T, error) {
if d.size == 0 {
return *new(T), errors.New("empty deque")
}
val := d.tail.val
if d.size == 1 {
d.tail = nil
d.head = nil
} else {
d.tail = d.tail.prev
d.tail.next = nil
}
d.size--
return val, nil
}
func (d *Deque[T]) GetLast() (T, error) {
if d.size == 0 {
return *new(T), errors.New("empty deque")
}
return d.tail.val, nil
}