go: add «641. Design Circular Deque»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
fd54db95cd
commit
b31c81e800
1 changed files with 86 additions and 0 deletions
86
go/design-circular-deque.go
Normal file
86
go/design-circular-deque.go
Normal file
|
@ -0,0 +1,86 @@
|
|||
package main
|
||||
|
||||
type MyCircularDeque struct {
|
||||
maxSize int
|
||||
|
||||
deque []int
|
||||
size int
|
||||
i int
|
||||
}
|
||||
|
||||
func Constructor(k int) MyCircularDeque {
|
||||
return MyCircularDeque{
|
||||
maxSize: k,
|
||||
deque: make([]int, k),
|
||||
size: 0,
|
||||
i: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) InsertFront(value int) bool {
|
||||
if this.IsFull() {
|
||||
return false
|
||||
}
|
||||
|
||||
this.i = (this.i - 1 + this.maxSize) % this.maxSize
|
||||
this.deque[this.i] = value
|
||||
this.size++
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) InsertLast(value int) bool {
|
||||
if this.IsFull() {
|
||||
return false
|
||||
}
|
||||
|
||||
this.deque[(this.i+this.size)%this.maxSize] = value
|
||||
this.size++
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) DeleteFront() bool {
|
||||
if this.IsEmpty() {
|
||||
return false
|
||||
}
|
||||
|
||||
this.size--
|
||||
this.i = (this.i + 1) % this.maxSize
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) DeleteLast() bool {
|
||||
if this.IsEmpty() {
|
||||
return false
|
||||
}
|
||||
|
||||
this.size--
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) GetFront() int {
|
||||
if this.IsEmpty() {
|
||||
return -1
|
||||
}
|
||||
|
||||
return this.deque[this.i]
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) GetRear() int {
|
||||
if this.IsEmpty() {
|
||||
return -1
|
||||
}
|
||||
|
||||
return this.deque[(this.i+this.size-1)%this.maxSize]
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) IsEmpty() bool {
|
||||
return this.size == 0
|
||||
}
|
||||
|
||||
func (this *MyCircularDeque) IsFull() bool {
|
||||
return this.size == this.maxSize
|
||||
}
|
Loading…
Reference in a new issue