数组实现一个简单的栈结构

时间:2020-09-16 12:46:27   收藏:0   阅读:67
public class Stack {
    private int maxSize=16;
    private int top;
    private int[] arr=null;

    public Stack(int maxSize) {
        if(maxSize<1){
            throw new RuntimeException("长度太小");
        }
        this.maxSize = maxSize;
        this.top = -1;
        this.arr = new int[maxSize];
    }
    public boolean isFull(){
        return top==maxSize-1;
    }

    public void  push(int i){
        if(isFull()){
            throw new RuntimeException("栈已满");
        }
        top++;
        arr[top]=i;
    }
    private boolean isEmpty(){
        return top==-1;
    }

    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("数据为空");
        }
        int res=arr[top];
        top--;
        return res;
    }
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("数据为空");
        }
        return arr[top];
    }

    public static void main(String[] args) {
        Stack stack = new Stack(5);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!