欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈--用简单数组实现(Java)

程序员文章站 2024-02-17 10:10:46
...

实现的方法:

push,pop,isStackFull,isStackEmpty,deleteStack。

class ArrayStack{
    private int top;
    private int capacity;
    private int[] array;
    public ArrayStack(){
        capacity=3;
        array=new int[capacity];
        top=-1;
    }

    public boolean isEmpty(){
        return (top==-1);
    }

    public boolean isStackFull(){
        return (top==capacity-1);
    }

    public void push(int date){
        if(isStackFull()){
            System.out.println("Stack overflow");
        }else {
            array[++top]=date;
        }
    }

    public int pop(){
        if(isEmpty()){
            System.out.println("Stack empty");
            return 0;
        }else {
            return array[top--];
        }
    }

    public void deleteStack(){
        top=-1;
    }
}

public class Main {

    public static void main(String[] args) {
        // write your code here
        ArrayStack arrayStack=new ArrayStack();
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        System.out.println(arrayStack.pop());
        System.out.println(arrayStack.pop());
        System.out.println(arrayStack.pop());
    }
}


相关标签: java stack array