Last active
June 10, 2022 07:04
-
-
Save sychonet/a011367f012294d90413a2230b51f3eb to your computer and use it in GitHub Desktop.
A basic implementation of circular queue in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this at https://go.dev/play/p/Oq0sQ9oE_HV