栈 (一)数组实现

1.代码

1.

package com.example.lib5.stack;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(10);
        boolean isFull=arrayStack.isFull();
        System.out.println("是否满了"+isFull);
        boolean isEmpty=arrayStack.isEmpty();
        System.out.println("是否为空"+isEmpty);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);
        arrayStack.push(5);
        arrayStack.push(8);
        int pop = arrayStack.pop();
        System.out.println("取出的值为"+pop);
        arrayStack.list();

    }

}
class ArrayStack{

    private int maxSize;
    private int[] stack;
    private int top=-1;

    public ArrayStack(int maxSize) {
        this.maxSize=maxSize;
        stack = new int[maxSize];
    }

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

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

    public void push(int value) {
        //判断是否满了
        if (isFull()) {
            System.out.println("满了无法添加");
            return;
        }
        //设置对应的值
        top++;
        stack[top]=value;
    }

    public int pop() {
        //判断是否为空
        if (isEmpty()) {
            throw new RuntimeException("栈空,没有数据");
        }
        int value=stack[top];
        //取出
        stack[top]=0;
        top--;
        return value;
    }

    public void list() {
        //判断是否为空
        if (isEmpty()) {
            System.out.println("为空");
            return;
        }
        //倒遍历打印
        System.out.println("遍历结果为-----------------------");
        for (int i = top; i > -1; i--) {
            System.out.println("遍历结果为"+stack[i]);
        }
    }
}

2.描述

1.栈有先进后出的特点,即进去1,2,3,出来就是3,2,1。跟队列是反过来的(队列是先进先出)

2.用数组实现栈,MaxTop表示最大值,Top表示栈里有多少个值,每次添加一就会top++,top=MaxTop-1的时候表示满了,top=-1表示栈空

在这里插入图片描述

3.反思总结

1.

2.

3.

4.

5.

6.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值