算法入門 - 基於動態數組的棧和隊列(Java版本)


之前我們學習了動態數組的實現,接下來我們用它來實現兩種數據結構——棧和隊列。首先,我們先來看一下棧。

一、什么是棧?

棧是計算機的一種數據結構,它可以臨時存儲數據。那么它跟數組有何區別呢?
我們知道,在數組中無論添加元素還是刪除元素,都可以根據索引位置或值進行操作,棧是否也支持這樣的操作呢?答案是不行,棧最大的特點就是后進先出(Last In First Out, LIFO):

棧雖然看似簡單,但是在計算機世界中有着非常重要的作用。比如在連續調用時,就利用了棧的特性:

    public static void addNum(){
        System.out.println("加法運算");
        Scanner scanner = new Scanner(System.in);
        System.out.print("請輸入整數a:");
        int a = scanner.nextInt();
        System.out.print("請輸入整數b:");
        int b = scanner.nextInt();
        System.out.println("a + b = " + (a + b));
    }

    public static void main(String[] args) {
        addNum();
    }

這里,在調用 addNum 方法時,內部又依次調用了兩次 Scanner 實現輸入。所以可以這么看,先調用了 addNum 方法,但是必須等待兩次 Scanner 調用完成后,addNum 方法才能結束:

了解了棧后進先出的特點,我們就可以使用動態數組進行模擬了。

1.使用動態數組模擬棧

模擬的關鍵點在於“后進”和“先出”,也就是說,如果使用數組模擬的話,入棧時需要從數組尾部添加元素(addLast),出棧時也從尾部出棧(removeLast):

所以這樣一來,數組頭部實際上是棧底,數組尾部是棧頂。
接下來我們就用代碼實現。

2.代碼實現

首先定義棧的接口,規范棧的操作:

package com.algorithm.stack;

public interface Stack <E> {
    void push(E element);   // 入棧
    E pop();                // 出棧
    E peek();               // 查看棧頂元素
    int getSize();          // 獲取棧長度
    boolean isEmpty();      // 判斷棧是否為空

}

按照剛才說的,只要分別使用動態數組的 addLast() 和 removeLast() 方法替代棧的 push() 和 pop() 方法即可:

package com.algorithm.stack;

import com.algorithm.dynamicarrays.Array;

// 使用動態數組實現棧結構
// 棧底: index = 0; 棧頂: index = size - 1 (push: O(1), pop: O(1))
// 如果棧頂設在index=0的位置,push和pop都將面臨較大開銷(O(n))
public class ArrayStack<E> implements Stack<E>{
    private Array<E> arr;    // 使用之前實現的Array動態數組模擬棧

    public ArrayStack(int capacity){
        arr = new Array<>(capacity);
    }

    public ArrayStack(){
        arr = new Array<>();
    }

    // 從棧頂壓入
    @Override
    public void push(E element){
        arr.addLast(element);
    }

    // 從棧頂彈出
    @Override
    public E pop(){
        return arr.removeLast();
    }

    // 從棧頂返回
    @Override
    public E peek(){
        return arr.getLast();
    }

    // 棧長度
    @Override
    public int getSize(){
        return arr.getSize();
    }

    // 棧容量
    public int getCapacity(){
        return arr.getCapacity();
    }

    // 判斷棧是否為空
    @Override
    public boolean isEmpty(){
        return arr.isEmpty();
    }

    @Override
    public String toString(){
        StringBuilder str = new StringBuilder();
        str.append(String.format("Stack: size = %d, capacity = %d\n[", getSize(), getCapacity()));
        for (int i=0; i<getSize(); i++) {
            str.append(arr.get(i));
            if (i < getSize() - 1) {
                str.append(", ");
            }
        }
        str.append("] top");    // 標識出棧頂位置
        return str.toString();
    }

    // main函數測試
    public static void main(String[] args) {
        ArrayStack<Integer> arrayStack = new ArrayStack<>();
        for (int i =0; i<5; i++){
            arrayStack.push(i);
            System.out.println(arrayStack);
        }
        // pop
        arrayStack.pop();
        System.out.println(arrayStack);
    }
}

/*
輸出結果:
Stack: size = 1, capacity = 10
[0] top
Stack: size = 2, capacity = 10
[0, 1] top
Stack: size = 3, capacity = 10
[0, 1, 2] top
Stack: size = 4, capacity = 10
[0, 1, 2, 3] top
Stack: size = 5, capacity = 10
[0, 1, 2, 3, 4] top
Stack: size = 4, capacity = 10
[0, 1, 2, 3] top
*/

結果符合預期。

3.時間復雜度分析

入棧對應的數組操作是 addLast(),我們可以通過查看該方法的具體實現進行分析:

    /**
     * 在指定位置添加元素
     * 指定位置處的元素需要向右側移動一個單位
     * @param index   索引
     * @param element 要添加的元素
     */
    public void add(int index, E element) {
        if (index < 0 || index > size) throw new IllegalArgumentException("Illegal index, index must > 0 and <= size!");
        // 數組滿員觸發擴容
        if (getSize() == getCapacity()) {
            resize(2 * getCapacity());  // 擴容為原數組的2倍
        }
        // 從尾部開始,向右移動元素,直到index
        for (int i = getSize() - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        // 添加元素
        data[index] = element;
        size++;
    }

    // 數組尾部添加元素
    public void addLast(E element) {
        add(getSize(), element);
    }

    /**
     * 刪除指定位置元素
     * 通過向左移動一位,覆蓋指定位置處的元素,實現刪除元素(data[size - 1] = null)
     * @param index 索引
     */
    public E remove(int index) {
        if (index < 0 || index > size) throw new IllegalArgumentException("Illegal index, index must > 0 and < size!");
        // 數組長度為0時拋出異常
        if (getSize() == 0) throw new IllegalArgumentException("Empty array!");
        E removedElement = data[index];
        // 向左移動元素
        for (int i = index; i < getSize() - 1; i++) {
            data[i] = data[i + 1];
        }
        // 將尾部空閑出的位置置為空,釋放資源
        data[getSize() - 1] = null;
        size--;
        // size過小觸發數組縮減
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) resize(getCapacity() / 2);
        return removedElement;
    }

    // 刪除尾部元素
    public E removeLast() {
        return remove(getSize() - 1);
    }

可以看出,每次從數組尾部添加元素時,add() 方法的 for 循環都無法滿足條件,等同於直接在 size 處添加元素,所以時間復雜度為 O(1)。如果再考慮數組滿員后觸發的 resize 操作,相當於是進行了 n+1 次 add() 操作后才會觸發 n次操作的 resize(移動n個元素至新數組),所以每次 add() 操作平均耗時為 \(\frac{2n+1}{n+1} \approx 2\),是一個與數組長度 n 無關的數,所以也可以看做是 O(1) 復雜度的。
同理,出棧對應的 removeLast() 的時間復雜度也是 O(1)。

二、什么是隊列?

理解了棧后,隊列就更簡單了。實際上,隊列是我們日常生活中幾乎每天都會碰到的。我們去超市買東西結賬時需要排隊,去銀行辦理業務時需要排隊,做核酸、打疫苗就更需要排隊了😂:

所以隊列是一種先進先出的數據結構。

1.使用動態數組模擬隊列

如果將隊列也轉換成數組,會是這樣:

可以看出,入隊的操作與入棧的實現方式相同,而出隊則是從數組頭部(removeFirst)。

2.代碼實現

同樣,我們先定義隊列接口:

package com.algorithm.queue;

public interface Queue<E> {
    void enqueue(E element);    // 入隊
    E dequeue();                // 出隊
    E getFront();               // 獲取隊首元素
    int getSize();              // 獲取隊列長度
    boolean isEmpty();          // 判斷隊列是否為空
}
package com.algorithm.queue;

import com.algorithm.dynamicarrays.Array;

// 使用動態數組實現隊列
public class ArrayQueue<E> implements Queue<E>{
    private Array<E> arr;    // 使用之前實現的Array動態數組模擬隊列

    public ArrayQueue(int capacity){
        arr = new Array<>(capacity);
    }

    public ArrayQueue(){
        arr = new Array<>();
    }

    // 隊首: index = 0; 隊尾: index = size - 1
    // 隊尾入隊
    @Override
    public void enqueue(E element){
        arr.addLast(element);
    }

    //隊首出隊
    @Override
    public E dequeue(){
        return arr.removeFirst();
    }

    // 隊首返回
    @Override
    public E getFront(){
        return arr.getFirst();
    }

    // 隊列長度
    @Override
    public int getSize(){
        return arr.getSize();
    }

    // 判斷隊列是否為空
    @Override
    public boolean isEmpty(){
        return arr.isEmpty();
    }

    // 隊列容量
    public int getCapacity(){
        return arr.getCapacity();
    }

    @Override
    public String toString(){
        StringBuilder str = new StringBuilder();
        str.append(String.format("Queue: size = %d, capacity: %d\ntop [", getSize(), getCapacity()));
        for (int i=0; i< getSize(); i++) {
            str.append(arr.get(i));
            if (i< getSize() - 1) {
                str.append(", ");
            }
        }
        str.append("] tail");    // 標識隊尾
        return str.toString();
    }

    // main函數測試
    public static void main(String[] args) {
        ArrayQueue<Integer> arrayQueue = new ArrayQueue<>();
        for (int i=0;i<5;i++){
            arrayQueue.enqueue(i);
            System.out.println(arrayQueue);
            if (i % 3 == 2){    // 每隔3個元素進行出隊操作
                arrayQueue.dequeue();
                System.out.println(arrayQueue);
            }
        }
    }
}

/*
輸出結果:
Queue: size = 1, capacity: 10
top [0] tail
Queue: size = 2, capacity: 10
top [0, 1] tail
Queue: size = 3, capacity: 10
top [0, 1, 2] tail
Queue: size = 2, capacity: 5
top [1, 2] tail
Queue: size = 3, capacity: 5
top [1, 2, 3] tail
Queue: size = 4, capacity: 5
top [1, 2, 3, 4] tail
*/

3.時間復雜度分析

入隊的時間復雜度與之前入棧相同,都是 O(1);而出隊由於是從數組頭部出,所以會觸發剩余元素向左移動,所以時間復雜度為 O(n)。

三、循環隊列

1.原理分析

這么一看,好像隊列的性能不如棧啊。如果能在出隊時不移動元素,那么出隊的時間復雜度也是O(1)了。我們先來看看不移動元素的話,會是什么情況:

看着有點暈,整個過程實際上是先入隊3、9、5,然后3出隊,4、2入隊,9出隊,最后1、7入隊。可以注意到,1入隊后,后面再無位置,但是可以往之前出隊過的位置繼續入隊。所以我們需要兩個參數,分別記錄隊列的首尾位置:

這下就清楚多了,所以要實現一個這樣首尾循環的隊列,主要有以下幾個要點

(1)當隊列為空時,front 和 tail 都為-1;
(2)第一個元素入隊時,front 和 tail 同時置為0;
(3)后續元素入隊時,只移動tail,但要注意tail從隊尾移到隊首的情形,所以下一個位置的索引為(tail + 1) % array.length;
(4)有元素出隊時,移動front,同時也要注意索引循環的問題;
(5)如果(tail + 1) % array.length == front,說明隊列已滿,則觸發擴容;
(6)如果 size 過小,則觸發隊列縮減。

這里需要注意的是,數組擴容和縮減后,需要將元素按照初始位置排列好

由此,我們就可以將初始的隊列升級為循環隊列了。

2.代碼實現

package com.algorithm.queue;

public class LoopQueue<E> implements Queue<E>{
    private E[] data;               // 存放數組元素
    private int front, tail, size;  // 分別記錄隊首、隊尾索引和數組長度

    public LoopQueue(int capacity){
        data = (E[])new Object[capacity];
        front = tail = -1;
        size = 0;
    }

    public LoopQueue(){
        this(10);
    }

    @Override
    public int getSize(){
        return size;
    }

    public int getCapacity(){
        return data.length;
    }

    // 判斷是否為空
    public boolean isEmpty(){
        return getSize() == 0;
    }

    // 獲取隊首元素
    @Override
    public E getFront(){
        if (isEmpty()) throw new IllegalArgumentException("Empty queue, enqueue first!");
        return data[front];
    }
    
    // 入隊
    @Override
    public void enqueue(E element){
        // 如果當前數組為空,則將隊首元素置為0(首次入隊)
        if (isEmpty()) front = 0;
        // 如果tail移動一位后等於front, 說明數組已滿員,則觸發擴容
        if ( (tail + 1) % getCapacity() == front && tail != -1) resize(2 * getCapacity());
        // 先移動tail
        tail = (tail + 1) % getCapacity();
        // 添加元素
        data[tail] = element;
        size++;
    }

    // 出隊
    public E dequeue(){
        if (isEmpty()) throw new IllegalArgumentException("Empty queue, enqueue first!");
        // 記錄待出隊元素
        E deElement = data[front];
        // 將front處的元素置為null
        data[front] = null;
        // 移動front
        front = (front + 1) % getCapacity();
        size--;
        // 如果size過小,則觸發縮減
        if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        // 如果出隊后隊列為空,則將front和tail同時置為-1
        if (isEmpty()) front = tail = -1;
        return deElement;
    }

    // 數組擴容/縮減
    public void resize(int newCapacity){
        // 創建新數組
        E[] newData = (E[])new Object[newCapacity];
        // 將原數組中的元素按順序放入新數組中
        for (int i=0; i<getSize(); i++) {
            newData[i] = data[(i +front) % getCapacity()];
        }
        // 重置front和tail
        front = 0;
        tail = getSize() - 1;
        // 將引用指向新數組
        data = newData;
    }

    @Override
    public String toString(){
        if (getSize() == 0) return "[]";
        StringBuilder str = new StringBuilder();
        str.append(String.format("Loop Queue: size = %d, capacity = %d\n[", getSize(), getCapacity()));
        // 從front開始遍歷元素
        for (int i=front; i!=tail; i=(i+1)%getCapacity()) {
            str.append(data[i]).append(", ");
        }
        str.append(data[tail]).append("]");
        return str.toString();
    }

    // main函數測試
    public static void main(String[] args) {
        LoopQueue<Integer> queue = new LoopQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            // 每次入隊后打印當前隊列
            System.out.println(queue);
            // 同時打印front和tail的索引位置
            System.out.printf("enqueue: front:%d, tail:%d%n", queue.front, queue.tail);
            // 滿足條件則進行出隊操作
            if (i % 2 == 0 && i != 0) {
                queue.dequeue();
                System.out.println(queue);
                System.out.printf("dequeue: front:%d, tail:%d%n", queue.front, queue.tail);
            }
        }
    }
}

/*
輸出結果:
Loop Queue: size = 1, capacity = 10
[0]
enqueue: front:0, tail:0
Loop Queue: size = 2, capacity = 10
[0, 1]
enqueue: front:0, tail:1
Loop Queue: size = 3, capacity = 10
[0, 1, 2]
enqueue: front:0, tail:2
Loop Queue: size = 2, capacity = 5
[1, 2]
dequeue: front:0, tail:1
Loop Queue: size = 3, capacity = 5
[1, 2, 3]
enqueue: front:0, tail:2
Loop Queue: size = 4, capacity = 5
[1, 2, 3, 4]
enqueue: front:0, tail:3
Loop Queue: size = 3, capacity = 5
[2, 3, 4]
dequeue: front:1, tail:3
Loop Queue: size = 4, capacity = 5
[2, 3, 4, 5]
enqueue: front:1, tail:4
Loop Queue: size = 5, capacity = 5
[2, 3, 4, 5, 6]
enqueue: front:1, tail:0
Loop Queue: size = 4, capacity = 5
[3, 4, 5, 6]
dequeue: front:2, tail:0
Loop Queue: size = 5, capacity = 5
[3, 4, 5, 6, 7]
enqueue: front:2, tail:1
Loop Queue: size = 6, capacity = 10
[3, 4, 5, 6, 7, 8]
enqueue: front:0, tail:5
Loop Queue: size = 5, capacity = 10
[4, 5, 6, 7, 8]
dequeue: front:1, tail:5
Loop Queue: size = 6, capacity = 10
[4, 5, 6, 7, 8, 9]
enqueue: front:1, tail:6

*/

最后的輸出有點長,不過通過這樣的測試,可以觀察隨着元素的增減,隊列的擴容和縮減的情況,以及 front 和 tail 索引位置的移動情況。

3.時間復雜度分析

我們主要就是將原先時間復雜度為O(n)的出隊操作升級為了O(1),入隊操作仍是O(1)。

總結

通過對動態數組的學習,並實現了棧和隊列兩種比較基礎的數據結構,讓我們能夠更深入的了解這些結構背后的原理,為我們今后學習更復雜的數據結構打下基礎。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM