使用棧Stack實現佇列Queue
阿新 • • 發佈:2019-02-14
如何只使用stack實現queue呢?由於stack是現進後出(FILO),而queue是先進先出的(FIFO)。也就是說stack進行了一次反向,進行兩次反向就能實現queue的功能,所以可以用兩個stack實現queue。 假設兩個棧inStack和outStack,且都為空。可以認為onStack提供入隊的功能,棧outStack提供出隊的功能。下面是入隊和出隊的具體演算法:(1)如果棧outStack不為空,直接彈出棧outStack頂部的資料;(2)如果棧outStack為空,則依次彈出棧inStack的資料,放入棧outStack中,再彈出棧outStack頂部的資料;實現的程式碼:
測試程式碼:
輸出:
- /**
- * 使用兩個棧來模擬佇列
- *
- * @param <T>
- *
- */
- publicclass SimulationQueue<T> {
- private Stack<T> inStack;
- private Stack<T> outStack;
- public SimulationQueue() {
- inStack = new Stack<T>();
- outStack = new
- }
- /**
- * 入隊
- *
- * @param t
- */
- publicvoid enqueue(T t) {
- inStack.push(t);
- }
- /**
- * 出隊
- */
- public T dequeue() {
- T temp = null;
- if (!outStack.isEmpty()) {
- temp = outStack.pop();
- } else {
- while (!inStack.isEmpty()) {
- temp = inStack.pop();
- outStack.push(temp);
- }
- if (!outStack.isEmpty()) {
- temp = outStack.pop();
- }
- }
- return temp;
- }
- /**
- * 佇列是否為空
- *
- * @return
- */
- publicboolean isEmpty() {
- return inStack.isEmpty() && outStack.isEmpty();
- }
- /**
- * 清空佇列
- */
- publicvoid clear() {
- inStack.clear();
- outStack.clear();
- }
- }
測試程式碼:
- publicstaticvoid main(String[] args) {
- SimulationQueue<String> queue = new SimulationQueue<String>();
- queue.enqueue("a");
- queue.enqueue("b");
- queue.enqueue("c");
- queue.enqueue("d");
- while(!queue.isEmpty()){
- System.out.println("當前出隊元素:"+queue.dequeue());
- }
- }
輸出: