mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
57 lines
1,002 B
Go
57 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();
|
||
|
*/
|