Created
December 23, 2022 22:47
-
-
Save abdulrahmanAlotaibi/4f4f96ea5eafa78b680304434cbb6849 to your computer and use it in GitHub Desktop.
Ring Buffer / Circular Queue
This file contains 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
type MyCircularQueue struct { | |
size int | |
head int | |
queue []int | |
} | |
func Constructor(k int) MyCircularQueue { | |
queue := make([]int, k) | |
size := 0 | |
head := 0 | |
return MyCircularQueue{ | |
queue:queue, | |
size:size, | |
head:head, | |
} | |
} | |
func (this *MyCircularQueue) EnQueue(value int) bool { | |
if this.IsFull(){ | |
return false | |
} | |
this.queue[(this.head + this.size) % cap(this.queue)] = value | |
this.size++ | |
return true | |
} | |
func (this *MyCircularQueue) DeQueue() bool { | |
if this.IsEmpty(){ | |
return false | |
} | |
this.head = (this.head+1) % cap(this.queue) | |
this.size-- | |
return true | |
} | |
func (this *MyCircularQueue) Front() int { | |
if this.IsEmpty(){ | |
return -1 | |
} | |
return this.queue[this.head] | |
} | |
func (this *MyCircularQueue) Rear() int { | |
if this.IsEmpty(){ | |
return -1 | |
} | |
return this.queue[(this.head + this.size -1) % cap(this.queue)] | |
} | |
func (this *MyCircularQueue) IsEmpty() bool { | |
return this.size == 0 | |
} | |
func (this *MyCircularQueue) IsFull() bool { | |
return this.size == cap(this.queue) | |
} | |
/** | |
* Your MyCircularQueue object will be instantiated and called as such: | |
* obj := Constructor(k); | |
* param_1 := obj.EnQueue(value); | |
* param_2 := obj.DeQueue(); | |
* param_3 := obj.Front(); | |
* param_4 := obj.Rear(); | |
* param_5 := obj.IsEmpty(); | |
* param_6 := obj.IsFull(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment