用數組簡單實現棧(stack)的基本操作

import java.util.Arrays;

//用數組實現棧
public class Stack {
    private int[] array;
    private int top;
    public Stack(int defaultCapacity){
        array = new int[defaultCapacity];
        top = 0;
    }
    public Stack(){
        this(20);
    }
    //入棧
    public void push(int val){
        if(top == array.length){
            array = Arrays.copyOf(array,array.length * 2);
        }
        array[top++] = val;
    }
    //刪除
    public void pop(){
        if(top <= 0){
            System.out.println("棧爲空,無法刪除元素");
            return;
        }
        top--;
        array[top] = 0;//可有可無,把所有空的置爲0
    }
    //返回棧頂元素
    public int top(){
        if(top <= 0){
            System.out.println("棧爲空,無法返回棧頂元素");
            return -1;
        }
        return array[top - 1];
    }
    //返回棧大小
    public int size(){
        return top;
    }
    //判空
    public boolean isEmpty(){
        return top == 0;
    }

    public void printStack(){
        for (int i = 0; i < array.length - 1; i++) {
            System.out.print(array[i]);
            System.out.print("->");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Stack stack = new Stack(20);
        for (int i = 0; i < 25; i++) {
            stack.push(i);
        }
        stack.printStack();
        stack.pop();
        //stack.pop();
        stack.printStack();
        System.out.println(stack.top());
        stack.push(100);
        stack.printStack();
        System.out.println(stack.isEmpty());
        System.out.println("size:" + stack.size());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章