顺序栈

2025-9-28 230 9/28
//栈初始化
private char[]data;//栈的元素
private int top;//栈顶指针
private int maxSize;//栈的大小

// 构造函数
public test(int size){
        this.maxSize=size;// 栈的大小
        this.data=new char[maxSize];
        this.top=-1;//栈顶指针
        }

// 获得栈顶元素
public char getTop(){//栈顶元素
        if(isEmpty()){
        throw new RuntimeException("栈为空");
        }
        return data[top];
        }

// 进栈
public void push(char element){
        if(isFull()){
        throw new RuntimeException("栈已满");
        }
        data[++top]=element;    // 先将top加1,再存储元素
        }

// 出栈
public char pop(){
        if(isEmpty()){
        throw new RuntimeException("栈为空");
        }
        return data[top--]; // 先返回栈顶元素,再将top减1
        }

// 判断栈是否为空
public boolean isEmpty(){
        return top==-1;   //当tap等于-1时栈为空,
        }

// 判断栈是否已满
public boolean isFull(){
        return top==maxSize-1;//为空时可在中栈添加元素
        }

 

- THE END -

dajavv

10月17日11:53

最后修改:2025年10月17日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论