首页 > 其他 > 详细

数据结构

时间:2020-11-10 23:42:48      阅读:43      评论:0      收藏:0      [点我收藏+]

用数组的方式实现

public class ArrayStack {
    private long[] array;  //数组方式实现
    private int top;  //栈顶
    private int size;  //栈内元素个数

    public ArrayStack(int maxsize) {  //初始化
        size = maxsize;
        array = new long[size];
        top = -1;
    }

    public long peek() {  //返回栈顶元素
        if (isEmpty()) {
            throw new RuntimeException("栈为空!");
        } else {
            System.out.println("栈顶元素为:" + array[top]);
            return array[top];
        }
    }

    public void push(long elem) {  //入栈
        if (isFull()) {
            throw new RuntimeException("栈已满!");
        }
        array[++top] = elem;
        System.out.println("栈中成功插入元素,该元素为:" + elem);
    }

    public void pop() {  //出栈
        if (isEmpty()) {
            throw new RuntimeException("栈为空!");
        }
        System.out.println("栈中元素成功被删除,该元素为:" + array[top]);
        top--;

    }

    public int size() {  //栈的元素个数
        return size;
    }

    public boolean isEmpty() {  //栈是否为空
        return top == -1;
    }

    public boolean isFull() {  //栈是否已满
        return top == size - 1;
    }
    
}

数据结构

原文:https://www.cnblogs.com/kwdlh/p/13956527.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!