[劍指offer] --6.用兩個棧來實現一個佇列
阿新 • • 發佈:2018-11-01
題目描述
用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { } public int pop() { } }
解題思路
public class Solution6 { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } }
- 2個棧,一個存入隊佇列,另一個需要當彈出佇列。
- 因為佇列是先進先出,棧是先進後出,所以需要將stack1的佇列彈出存入stack2,保持彈出的順序和存入順序一樣,模擬佇列效果