數據結構與算法 使用數組實現棧(stack)

棧這種數據結構有FILO(First-In-Last-Out)的特性,恰好和隊列FIFO的特性相異。前面我們介紹了隊列也通過代碼實現了以數組爲基礎結構實現的隊列,這篇博客我們來介紹Stack,並且使用數組來實現 (鏈表實現性能稍差)。

  • 棧的結構像桶一樣,只不過每次只能放入和取出一個元素,所以Stack纔有FILO這種特性。
  • 棧的底部被成爲棧底(Bottom),頂部稱爲棧頂(top)。
  • 每次把元素放入棧入棧被稱爲入棧(Push),最先入棧的元素被壓在棧底。
  • 每次把元素取出棧被稱爲入棧(Pop),最先出棧的元素是在棧頂的元素。

在這裏插入圖片描述
在這裏插入圖片描述

  • 在實現代碼前,我們來規定:
  1. 棧的最多能容納MaxSize個元素。
  2. 有個虛擬的指針p(整數類型的變量)標記棧頂;當棧空時,p等於-1;當棧滿時,p等於MaxSize - 1。
  • 數組實現棧:
public class ArrayStack {
    private int MaxSize;
    private int p;
    private int [] stack;

    public ArrayStack(int MaxSize){
        this.MaxSize = MaxSize;
        this.p = -1;
        this.stack = new int[MaxSize];
    }

    /**
     * Judge if the stack is full.
     * @return
     */
    public boolean isFull(){
        return this.p == this.MaxSize - 1;
    }

    /**
     * Push a element into the stack.
     * @param element
     */
    public void Push(int element){
        if(!this.isFull()){
            this.stack[++ this.p] = element;
            return;
        }
        System.out.println("Stack is full.");
    }

    /**
     * Judge if the stack is empty.
     * @return
     */
    public boolean isEmpty(){
        return this.p == -1;
    }

    /**
     * Pop a element out.
     * @return
     */
    public int Pop(){
        if(this.isEmpty()){
            System.out.println("The stack is empty");
            return Integer.MIN_VALUE;
        }
        return this.stack[this.p --];
    }

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(10);
        for(int i = 1;i <= 10;i ++){
            arrayStack.Push(i);
        }
        for (int j = 0;j < 10;j ++){
            System.out.println(arrayStack.Pop());
        }
    }
}
  • 這裏巧用了自增、自減運算符,因此代碼量比較少。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章