首先需要明确栈和队列的特性,栈的特点是先进后出,即最后被压入(push)栈的元素会第一个被弹出(pop);队列的特点是先进先出,即第一个进入队列元素将会第一个出来。本体的思路是:将元素全部压入(push)stack1中,此时stack2为空;元素全部压入完毕,将stack1中的元素弹出(pop)并将其压入(push)stack2中,全部压入(push)完毕,将stack2中的元素取出。
Java代码实现:
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); //将元素压入stack1
}
public int pop() throws Exception{
//判断两个栈是否都为空,如果都为空则抛出一异常
if(stack1.isEmpty() && stack2.isEmpty()){
throw new Exception("栈为空!");
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){ //在stack2为空且stack1不为空时,将stcak1中的元素取出压入stack2
stack2.push(stack1.pop());
}
}
return stack2.pop(); //取出stack2中的元素即可
}
}