mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
61 lines
1 KiB
Go
61 lines
1 KiB
Go
package main
|
|
|
|
import (
|
|
"slices"
|
|
)
|
|
|
|
type MyQueue struct {
|
|
asQueue []int
|
|
asStack []int
|
|
}
|
|
|
|
func NewQueue() MyQueue {
|
|
return MyQueue{
|
|
asQueue: make([]int, 0, 16),
|
|
asStack: make([]int, 0, 16),
|
|
}
|
|
}
|
|
|
|
// [XXX] Uncomment for LeetCode
|
|
// func Constructor() MyQueue {
|
|
// return NewQueue()
|
|
// }
|
|
|
|
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();
|
|
*/
|