题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析:
以栈A为基准,入队列全部入A,出队列的时候,将A中的数据依次出栈并且放入B,然后从B出队列,出完队列之后,再将B中的数据出栈并入A。
代码:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 =
new Stack<Integer>();
Stack<Integer> stack2 =
new Stack<Integer>();
public void push(
int node) {
stack1.push(node);
}
public int pop() {
while(!stack1.empty())
{
stack2.push(stack1.pop());
}
int temp = stack2.pop();
while(!stack2.empty())
{
stack1.push(stack2.pop());
}
return temp;
}
}
源码可以在我的github“栈”下的Solution.java中找到。
转载请注明原文地址: https://ju.6miu.com/read-1304665.html