棧(Java實現)

package ch03; public class MyStack { // 底層實現是一個數組
    private long[] arr; private int top; /** * 默認的構造方法 */
    public MyStack() { arr = new long[10]; top = -1; } /** * 帶參數構造方法,參數爲數組初始化大小 */
    public MyStack(int maxsize) { arr = new long[maxsize]; top = -1; } /** * 添加數據 */
    public void push(int 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 == arr.length - 1; } }

 

package ch03; public class TestMyStack { public static void main(String[] args) { MyStack ms = new MyStack(4); ms.push(23); ms.push(12); ms.push(1); ms.push(90); System.out.println(ms.isEmpty()); System.out.println(ms.isFull()); System.out.println(ms.peek()); System.out.println(ms.peek()); while(!ms.isEmpty()) { System.out.print(ms.pop() + ","); } System.out.println(ms.isEmpty()); System.out.println(ms.isFull()); } }
相關文章
相關標籤/搜索