標籤: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資料結構之棧