题目描述
我将队列中的元素定义为int类型。
首先要解决这个问题我们就需要明白一个问题:
什么是栈?
什么是队列?
栈是先进后出的,而队列是先进先出的:
即输入顺序是1,2,3,4,5
队列的pop是1
栈的pop是5
了解了这俩个的定义,接下来就简单就的多了:
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.isEmpty()){//判断栈1为不为空
stack2.push(stack1.pop());//将栈1中的所有数放入到栈2中
}
int x=stack2.pop();//栈2栈顶元素出栈,例子中出来的元素为1
while(!stack2.isEmpty()){//判断栈2为不为空
stack1.push(stack2.pop());//将栈2剩余的元素放入到栈1中
}
return x;
}