数据结构之栈

  • 先入后出(FILO)的有序列表。
  • 限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。

栈示意图

代码实现

package org.example.data.structure.stack;

/**
 * @author xzy
 * @since 2024/9/7 10:37
 */
public class ArrayStack {

    /**
     * 栈详情
     */
    private int[] content;

    /**
     * 栈大小
     */
    private int size;

    /**
     * 栈顶坐标
     */
    private int top;

    public ArrayStack(int size) {
        content = new int[size];
        this.size = size;
        top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == (size - 1);
    }

    /**
     * 入栈操作
     */
    public boolean push(int data) {
        if (isFull()) {
            System.out.println("栈已满");
            return false;
        }
        top++;
        content[top] = data;
        return true;
    }

    /**
     * 出栈操作
     */
    public int pop() {
        if (isEmpty()) {
            System.out.println("栈内元素为空, 返回默认值-1");
            return -1;
        }
        int result = content[top];
        top--;
        return result;
    }

    /**
     * 获取栈内元素, 从栈顶到栈底
     */
    public int[] list() {
        if (isEmpty()) {
            return new int[0];
        }
        int[] result = new int[top + 1];
        for (int i = 0, j = top; i <= top; i++, j--) {
            result[i] = content[j];
        }
        return result;
    }

}

源码与测试案例

gitee地址

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值