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

2021-03-29 12:28

阅读:711

标签:this   col   ati   his   ==   class   bool   ack   pre   

public class Stack {
    private int maxSize=16;
    private int top;
    private int[] arr=null;

    public Stack(int maxSize) {
        if(maxSize){
            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());
    }
}

 

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

标签:this   col   ati   his   ==   class   bool   ack   pre   

原文地址:https://www.cnblogs.com/yangxiaohui227/p/13606134.html


评论


亲,登录后才可以留言!