LeetCode/go/implement-queue-using-stacks.go
Matej Focko 47c6862e92
go: add «232. Implement Queue using Stacks»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-01-29 12:36:17 +01:00

56 lines
1,002 B
Go

package implement_queue_using_stacks
import (
"slices"
)
type MyQueue struct {
asQueue []int
asStack []int
}
func Constructor() MyQueue {
return MyQueue{
asQueue: make([]int, 0, 16),
asStack: make([]int, 0, 16),
}
}
func (this *MyQueue) Push(x int) {
this.asStack = append(this.asStack, x)
}
func (this *MyQueue) ReverseIfNeeded() {
if len(this.asQueue) > 0 {
return
}
slices.Reverse(this.asStack)
this.asQueue = this.asStack
this.asStack = make([]int, 0, 16)
}
func (this *MyQueue) Pop() int {
result := this.Peek()
this.asQueue = this.asQueue[:len(this.asQueue)-1]
return result
}
func (this *MyQueue) Peek() int {
this.ReverseIfNeeded()
return this.asQueue[len(this.asQueue)-1]
}
func (this *MyQueue) Empty() bool {
return len(this.asStack) == 0 && len(this.asQueue) == 0
}
/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/