資料結構複習:棧-Java數組實現

來源:互聯網
上載者:User

  棧是一種"後進先出(LIFO)"的資料結構.最近壓入的資料項目總是位於棧頂的.

   首先我們先定義一個Stack Interface,我們把他定義成泛型的.

 

/** * Stack介面 * @author Chris Wang * * @param <E> */public interface Stack<E> {    /**       * 判斷棧是否為空白     * @return       */      public boolean isEmpty();      /**       * 返回棧中元素個數       * @return       */      public int size();      /**       * 入棧       * @param target       *        */      public void push(E target);      /**       * 出棧       * @return E       */      public E pop();      /**       * 返回棧頂元素,並不出棧       * @return       */      public E top();           }

 

然後進行利用Java中的數組實現ArrayStack,下面是代碼:

Code

/**

* 一個基於數組的棧實現

* 
* @author Chris Wang  
* @param <E>

 */

public class ArrayStack<E> implements Stack<E> {

    /**

     * 表示要存入棧裡的元素

     */

    private E[] data;

    /**

     * 表示當前棧的容量

     */

    private int size = 0;

    public ArrayStack() {

        data = (E[]) new Object[10];

    //一開始的時候 棧中元素為空白

        size = 0;

    }

    public int size() {

        return size;

    }

    public boolean isEmpty() {

        return size < 1;

    }

    /**

     * 返回棧頂元素,但是不出棧

     */

    public E top() {

        if (isEmpty()) {

            throw new RuntimeException("鏈表為空白!!");

        }

        return data[size-1];

    }

    /**

     * 出棧

     */

    public E pop() {

        if (isEmpty()) {

            throw new RuntimeException("鏈表為空白!!");

        }

        // 先儲存那個棧頂元素

        E element = data[size - 1];

        // 然後清空棧頂元素,

        data[size] = null;

        //棧中元素減少一個

        size--;

        return element;

    }

    /**

     * 入棧的時候先判斷 棧是否已滿,如棧滿就擴充

     */

    public void push(E target) {

        if(target==null)

            throw new RuntimeException("插入的元素不可為NULL");

        if (isFull()) {

            enlarge();

        }

        size++;

        // 往棧頂添加一個元素

        data[size - 1] = target;

        

    }

    /**

     * 擴充數組長度 注意:一般是判斷棧滿以後 才擴充 擴充為原數組的兩倍長度

     */

    public void enlarge() {

        E[] newData = (E[]) new Object[data.length * 2];

        for (int i = 0; i < size; i++) {

            newData[i] = data[i];

        }

        data = newData;

    }

    /**

     * 如果數組的長度 已經等於 放入棧中的元素數量 則表示 棧已經滿了

     * 
     * @return

     */

    public boolean isFull() {

        return data.length == size;

    }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.