2024-06-16 11:44:08 +02:00
|
|
|
package main
|
2024-01-29 12:36:17 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"slices"
|
|
|
|
)
|
|
|
|
|
|
|
|
type MyQueue struct {
|
|
|
|
asQueue []int
|
|
|
|
asStack []int
|
|
|
|
}
|
|
|
|
|
2024-06-16 11:44:08 +02:00
|
|
|
func NewQueue() MyQueue {
|
2024-01-29 12:36:17 +01:00
|
|
|
return MyQueue{
|
|
|
|
asQueue: make([]int, 0, 16),
|
|
|
|
asStack: make([]int, 0, 16),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-16 11:44:08 +02:00
|
|
|
// [XXX] Uncomment for LeetCode
|
|
|
|
// func Constructor() MyQueue {
|
|
|
|
// return NewQueue()
|
|
|
|
// }
|
|
|
|
|
2024-01-29 12:36:17 +01:00
|
|
|
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();
|
|
|
|
*/
|