题目描述
使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
题解
- 栈的特点是先进后出,队列的特点是先进先出;
- 定义两个栈,数据栈和辅助栈
- 每次push时将新来的元素压入数据栈中
- 每次pop时,首先判断辅助栈中是否为空,
- 若辅助栈不空则直接弹出辅助栈栈顶元素
- 若辅助栈为空,则将数据栈中的元素依次全部压入辅助栈中,然后弹出辅助栈栈顶元素
算法
public class MyQueue {
private Stack<Integer> stack;
/** Initialize your data structure here. */
public MyQueue() {
stack=new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
Stack<Integer> tempS=new Stack<>();
while(!stack.isEmpty()) {
tempS.push(stack.pop());
}
tempS.push(x);//确保新加入的元素在栈的最顶端
while(!tempS.isEmpty()) {
stack.push(tempS.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int x=-1;
if(empty()==false) {
x=stack.pop();
}
return x;
}
/** Get the front element. */
public int peek() {
int x=-1;
if(empty()==false) {
x=stack.peek();
}
return x;
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack.isEmpty())
return true;
else
return false;
}
}

4817

被折叠的 条评论
为什么被折叠?



