使用两个 stack 来实现 queue 的功能
// Author: majianyu
// Create Date: 2019-01-31
// 功能:
// version V1.0
package stack_queue
const MyArraySize = 1000
type MyStack struct {
top int
data [MyArraySize]int
}
func (this *MyStack) Push(i int) bool {
if this.top >= MyArraySize {
return false
}
this.data[this.top] = i
this.top ++
return true
}
func (this *MyStack) Pop() (int, bool) {
if this.top == 0 {
return 0, false
}
this.top --
n := this.data[this.top]
return n, true
}
func (this *MyStack) Peek() int {
if this.top == 0 {
return -1
}
return this.data[this.top-1]
}
type MyQueue struct {
input *MyStack
output *MyStack
}
/** Initialize your data structure here. */
func Constructor() MyQueue {
return MyQueue{&MyStack{}, &MyStack{}}
}
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
this.input.Push(x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
if this.output.top == 0 {
this.swap()
}
n, _ := this.output.Pop()
return n
}
func (this *MyQueue) swap() {
for {
i, ok := this.input.Pop()
if !ok {
break
}
this.output.Push(i)
}
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
if this.output.top == 0 {
this.swap()
}
return this.output.Peek()
}
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
if this.input.top == 0 && this.output.top == 0 {
return true
}
return false
}