1.基础知识
(1)队列的特点是先进先出;
(2)栈的特点是先进后出;
(3)存数据很容易,直接将数据存入stack1中;
(4)关键在于取数据,实现的难点怎么由先进后出变为先进先出,所以很容易就想到可以利用stack2,取数据时将数据从stack1先后取出存入stack2中,然后再从stack2中取出来的就是先进先出的顺序了。
2.图示理解
(1)stack1用于push数据,stack2用于pop数据。
(2)当stack2没有数据,stack1有数据时,将stack1的数据全部存入stack2中,再进行pop操作;
(3)当stack2有数据就直接pop。
3.代码
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() {
if(stack1.isEmpty()&&stack2.isEmpty())
throw new RuntimeException("Queue is empty!");
int node;
//运行到这儿的时候,总有一个栈不是空的,
//但假如stack2是空的,就需要将stack1的所有元素存入stack2中
//最终从stack2中取出,下面代码就是保证stack2不为空
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
node=stack1.pop();
stack2.push(node);
}
}
return stack2.pop();
}
}