JAVA:使用棧實現一個隊列

使用棧實現一個隊列,須要弄清楚棧和隊列的區別:java

棧:先進後出;測試

隊列:先進先出。spa

實現思路:

1)經過兩個棧(pushStack / popStack)對倒,確保 popStack 棧的出棧順序與隊列出列一致。code

2)核心難點在加入隊列操做,假設隊列中已經加入一、二、三、4,加入5的過程:blog

2.1)假設已經加入1/2/3/4隊列

2.2)把popStack中的數據導入pushStackit

2.3)pushStack加入5io

2.4)把pushStack中的數據導入popStackclass

流程示意圖以下:import

實現代碼:

import java.util.Stack;

public class QueueWithStack<T> {
    /**
     * Test 測試代碼
     */
    public static void main(String[] args) {
        QueueWithStack<Integer> queue = new QueueWithStack<>();
        queue.add(1);
        System.out.println("入隊列:1");
        queue.add(2);
        System.out.println("入隊列:2");
        queue.add(3);
        System.out.println("入隊列:3");
        queue.add(4);
        System.out.println("入隊列:4");

        System.out.println("出隊列:" + queue.pop());
        System.out.println("出隊列:" + queue.pop());
        
        queue.add(5);    
        System.out.println("入隊列:5");
        queue.add(6);
        System.out.println("入隊列:6");
        System.out.println("====================");
        while (false == queue.isEmpty()) {
            System.out.println("出隊列:" + queue.pop());
        }

        System.out.println("隊列內元素個數:" + queue.size());
    }

    // 入棧是,將數據寫入該集合,而後在推向pop集合。
    private Stack<T> pushStack = null;
    // 出站時,讀取該集合
    private Stack<T> popStack = null;

    public QueueWithStack() {
        pushStack = new Stack<>();
        popStack = new Stack<>();
    }

    public boolean isEmpty() {
        return popStack.isEmpty();
    }

    public int size() {
        return popStack.size();
    }

    public void add(T t) {
        while (false == popStack.isEmpty()) {
            T val = popStack.pop();
            pushStack.push(val);
        }

        pushStack.add(t);

        while (false == pushStack.isEmpty()) {
            T val = pushStack.pop();
            popStack.push(val);
        }

    }

    /**
     * 從隊列中取出數據,並從隊列中移除數據
     */
    public T pop() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty.");
        }
        return popStack.pop();
    }

    /**
     * 獲取棧頂元素,但不會從隊列中移除數據
     */
    public T peek() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty.");
        }
        return popStack.peek();
    }
}

打印結果:

入隊列:1
入隊列:2
入隊列:3
入隊列:4
出隊列:1
出隊列:2
入隊列:5
入隊列:6
====================
出隊列:3
出隊列:4
出隊列:5
出隊列:6
隊列內元素個數:0
相關文章
相關標籤/搜索