java實現棧的簡單操作

-rainbow-發表於2018-11-16
public class stract {
    public static void main(String[] args) {
        MyStack stack = new MyStack(20);
 
        stack.push(10);
        stack.push(20);
        stack.push(30);
 
        System.out.println(stack);
        System.out.println(stack.peek());
        stack.pop();
        System.out.println(stack); 
        stack.pop();
        System.out.println(stack);
    }
}

class MyStack {
    // 底層用陣列實現
    private long[] arr;

    private int pop;

    public MyStack() {
        arr = new long[10];
        pop = -1;
    }
 
    public MyStack(int maxsize) {
        arr = new long[maxsize];
        pop = -1;
    }
 
    public void push(long data) { //入棧
        arr[++pop] = data;
    }
 
    public long pop() {//彈棧
        return arr[pop--];
    }
 
    public long peek() {//檢視棧頂資料
        return arr[pop];
    }
 
    public String list() {//遍歷資料
        String str = "";
        for (int i = 0; i <= pop; i++) {
            str += arr[i] + " ";
        }
        return str;
    }
 
    public String toString() {
        return list();
    }
}

 

相關文章