Skip to content

Instantly share code, notes, and snippets.

@sychonet
Last active June 10, 2022 07:04
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 sychonet/a011367f012294d90413a2230b51f3eb to your computer and use it in GitHub Desktop.
Save sychonet/a011367f012294d90413a2230b51f3eb to your computer and use it in GitHub Desktop.
A basic implementation of circular queue in Golang
// Implementation of circular queue
package main
import "fmt"
type MyCircularQueue struct {
data []int
head int
tail int
size int
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{
data: make([]int, k),
tail: -1,
head: -1,
size: k,
}
}
func (this *MyCircularQueue) EnQueue(value int) bool {
if !this.IsFull() {
this.tail = (this.tail + 1) % this.size
this.data[this.tail] = value
if this.head == -1 {
this.head++
}
return true
}
return false
}
func (this *MyCircularQueue) DeQueue() bool {
if this.head == this.tail && this.head > -1 {
// this condition implies that there is only one element in the queue
// hence we are re-initializing the values for head and tail
this.head = -1
this.tail = -1
return true
}
if !this.IsEmpty() {
this.head = (this.head + 1) % this.size
return true
}
return false
}
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.data[this.head]
}
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
return this.data[this.tail]
}
func (this *MyCircularQueue) IsEmpty() bool {
if this.tail == -1 && this.head == -1 {
return true
}
return false
}
func (this *MyCircularQueue) IsFull() bool {
if this.tail > -1 && (this.tail+1)%this.size == this.head {
return true
}
return false
}
func main() {
cq := Constructor(3)
fmt.Println(cq.EnQueue(5))
fmt.Println(cq.DeQueue())
fmt.Println(cq.Front())
fmt.Println(cq.Rear())
fmt.Println(cq.IsEmpty())
fmt.Println(cq.IsFull())
}
@sychonet
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment