/
queue.go
81 lines (64 loc) · 1.25 KB
/
queue.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
package main
import (
"fmt"
)
type Queue interface {
Cap() int64
Len() int64
Push(element interface{}) error
Pop() interface{}
}
type LLNode struct {
data interface{}
next *LLNode
}
// Queue represents FIFO Queue data structure (linked list)
type LLQueue struct {
head, tail *LLNode
size, items int64
}
func NewLLQueue(size ...int64) *LLQueue {
queue := &LLQueue{}
queue.size = -1
if len(size) > 0 {
queue.size = size[0]
}
return queue
}
// Return the Queue max capacity(size)
func (queue *LLQueue) Cap() int64 {
return queue.size
}
// Return the Queue current length
func (queue *LLQueue) Len() int64 {
return queue.items
}
// Push an element at the end of the queue
func (queue *LLQueue) Push(element interface{}) error {
if queue.items == queue.size {
return fmt.Errorf(
"Can't push %v, Queue beyoud limits (%d)", element, queue.size)
}
n := &LLNode{data: element}
if queue.tail == nil {
queue.tail = n
queue.head = n
} else {
queue.tail.next = n
queue.tail = n
}
queue.items++
return nil
}
// Pop an element from the head of the queue
func (queue *LLQueue) Pop() interface{} {
if queue.items == 0 {
return nil
}
head := queue.head
data := head.data
queue.head = head.next
head = nil
queue.items--
return data
}