LeetCode/go/implement-queue-using-stacks.go

57 lines
1,002 B
Go
Raw Normal View History

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();
*/