Java資料結構之棧

來源:互聯網
上載者:User

標籤:java   資料結構   棧   

package com.xingej.algorithm.datastructure.stack;/** * 資料結構之棧Stack *  * 以long類型為測試案例 *  * @author erjun 2017年12月4日 下午10:22:34 */public class LongStack {    // 底層資料存放區    private long[] arr;    // 最大元素數量    private int maxSize;    // 當前元素的指標    private int top;    public LongStack(int maxSize) {        this.maxSize = maxSize;        arr = new long[maxSize];        top = -1;// 預設值為-1,棧裡沒有元素    }    // 添加資料    public void push(long value) {        arr[++top] = value;    }    // 查看、並刪除元素資料    public long pop() {        return arr[top--]; // 先返回,然後,指標再減一    }    // 僅僅查看元素    public long peek() {        return arr[top];    }    // 查看當前棧空間是否為空白    public boolean isEmpty() {        return top == -1;    }    // 查看當前棧空間是否已經滿了    public boolean isFull() {        return top == (maxSize - 1);    }}


測試案例:

package com.xingej.algorithm.datastructure.stack;import org.junit.Test;/** * 棧的特點:先進後出; *  * 棧和隊列的區別? *  * 棧的主要組成:一個存資料的容器,如數組,或者鏈表;一個指標;其他API行為都是圍繞容器進行的 *  * 隊列的主要組成:一個存資料的容器,如數組,或者鏈表;兩個指標。 *  * 不適合大量儲存,只是實現某種演算法的一種手段吧, *  * 受限訪問方式 *  * @author erjun 2017年12月6日 上午9:11:40 */public class LongStackTest {    @Test    public void test() {        LongStack theStack = new LongStack(10);        theStack.push(29);        theStack.push(2);        theStack.push(9);        theStack.push(5);        while (!theStack.isEmpty()) {            System.out.print(theStack.pop() + " ");        }        System.out.println();    }}


代碼已上傳到git上:

https://github.com/xej520/xingej-algorithm












Java資料結構之棧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.