题目
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
分析
用两个栈即可实现队列,push不变,只要在pop时候把push的栈,导入到另外一个栈,即实现了栈的倒置,也就是队列。A栈后进先出,比如push进去1 2 3 4 5,那么出栈就是5 4 3 2 1。将出栈的元素再入栈到栈B,则变成5 4 3 2 1。所以1又到了第一位。
解法
type MyQueue struct {
In []int
Out []int
}
/** Initialize your data structure here. */
func Constructor() MyQueue {
return MyQueue{
}
}
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
this.In = append(this.In, x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
if len(this.Out) == 0 {
for len(this.In) > 0 {
this.Out = append(this.Out, this.In[len(this.In)-1])
this.In = this.In[:len(this.In)-1]
}
}
pop := this.Out[len(this.Out)-1]
this.Out = this.Out[:len(this.Out)-1]
return pop
}
/** Get the front element. */
func (this *MyQueue) Peek() int {
if len(this.Out) == 0 {
for len(this.In) > 0 {
this.Out = append(this.Out, this.In[len(this.In)-1])
this.In = this.In[:len(this.In)-1]
}
}
return this.Out[len(this.Out)-1]
}
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
return len(this.In) == 0 && len(this.Out) == 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();
*/