码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-09-16 12:46:27      阅读:67      评论:0      收藏:0      [点我收藏+]

标签: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<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());
    }
}

 

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!