思路:
两个栈。当有输出的时候。如果B里有东西就pop.没有的话把所有A里面的东西拿出来放入B。所有的入队全部放在A里面。
import java.util.Stack;
class MyQueue {
// Push element x to the back of queue.
Stack<Integer> stackA=new Stack<Integer>();
Stack<Integer> stackB=new Stack<Integer>();
boolean isOut=true;
public void push(int x) {
stackA.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(stackB.isEmpty())
{
while(!stackA.isEmpty())
{
stackB.push(stackA.pop());
}
}
stackB.pop();
}
// Get the front element.
public int peek() {
if(stackB.isEmpty())
{
while(!stackA.isEmpty())
{
stackB.push(stackA.pop());
}
}
return stackB.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stackA.isEmpty()&&stackB.isEmpty();
}
}
本文介绍了一种使用两个栈来实现队列的方法。通过将入队操作放置在一个栈中,并在需要出队时将该栈的数据倒置到另一个栈来完成。这种方式能够有效地模拟队列的先进先出特性。
273

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



