Skip to content

Commit c783fd1

Browse files
committedFeb 27, 2023
Implement fixed size Deque
1 parent 3bdf103 commit c783fd1

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
 

‎deque/fixed_size_deque.go

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package deque
2+
3+
type FixedSizeDeque struct {
4+
items [5]int
5+
front int
6+
back int
7+
}
8+
9+
func (d *FixedSizeDeque) EnqueueFront(item int) bool {
10+
if d.IsFull() {
11+
return false
12+
}
13+
d.front = (d.front - 1 + len(d.items)) % len(d.items)
14+
d.items[d.front] = item
15+
return true
16+
}
17+
18+
func (d *FixedSizeDeque) EnqueueBack(item int) bool {
19+
if d.IsFull() {
20+
return false
21+
}
22+
d.items[d.back] = item
23+
d.back = (d.back + 1) % len(d.items)
24+
return true
25+
}
26+
27+
func (d *FixedSizeDeque) DequeueFront() (int, bool) {
28+
if d.IsEmpty() {
29+
return 0, false
30+
}
31+
front := d.items[d.front]
32+
d.front = (d.front + 1) % len(d.items)
33+
return front, true
34+
}
35+
36+
func (d *FixedSizeDeque) DequeueBack() (int, bool) {
37+
if d.IsEmpty() {
38+
return 0, false
39+
}
40+
d.back = (d.back - 1 + len(d.items)) % len(d.items)
41+
rear := d.items[d.back]
42+
return rear, true
43+
}
44+
45+
func (d *FixedSizeDeque) IsEmpty() bool {
46+
return d.front == d.back
47+
}
48+
49+
func (d *FixedSizeDeque) IsFull() bool {
50+
return (d.back+1)%len(d.items) == d.front
51+
}
52+
53+
func (d *FixedSizeDeque) Size() int {
54+
if d.IsEmpty() {
55+
return 0
56+
}
57+
return (d.back - d.front + len(d.items)) % len(d.items)
58+
}

0 commit comments

Comments
 (0)
Please sign in to comment.