題目描述
用兩個棧來實現(xiàn)一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
/**
* Created by ZengXihong 2019-05-30.
*/
import java.util.Stack;
/**
* 題目描述
* 用兩個棧來實現(xiàn)一個隊列,完成隊列的Push和Pop操作。
* 隊列中的元素為int類型。
*/
/**
* 棧 先進后出
* 隊列 先進先出
*/
public class Solution5 {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
// 將數(shù)據(jù)都放到stack1 中 ,先進去的在 stack1 棧底
public void push(int node) {
stack1.push(node);
}
// 當要出棧時,先判斷 stack2 是否為空,如果為空,則將stack1 中的數(shù)據(jù)出棧并且入棧 stack2 中
// 這樣原本stack1 中的棧底元素就在stack2 的棧頂 ,再stack2 出棧就達到了最先進的數(shù)據(jù)最先出去,即隊列
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}