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();
}
}