Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created June 6, 2023 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAlchemistKE/473f76428260b0ba836dbba3e0d0eda3 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/473f76428260b0ba836dbba3e0d0eda3 to your computer and use it in GitHub Desktop.
package main
type CircularQueue struct {
items []interface{}
head int
tail int
size int
}
func NewCircularQueue(k int) *CircularQueue {
return &CircularQueue{
items: make([]interface{}, k),
head: -1,
tail: -1,
size: 0,
}
}
func (cq *CircularQueue) Enqueue(item interface{}) bool {
if cq.IsFull() {
return false
}
if cq.IsEmpty() {
cq.head = 0
}
cq.tail = (cq.tail + 1) % len(cq.items)
cq.items[cq.tail] = item
cq.size++
return true
}
func (cq *CircularQueue) Dequeue() interface{} {
if cq.IsEmpty() {
return nil
}
item := cq.items[cq.head]
if cq.head == cq.tail {
cq.head = -1
cq.tail = -1
} else {
cq.head = (cq.head + 1) % len(cq.items)
}
cq.size--
return item
}
func (cq *CircularQueue) IsEmpty() bool {
return cq.size == 0
}
func (cq *CircularQueue) IsFull() bool {
return cq.size == len(cq.items)
}
func (cq *CircularQueue) GetSize() int {
return cq.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment