java数据结构与算法数组模拟栈(含完整Demo)

579 阅读2分钟

什么是栈:

就像是手枪压子弹一样,第一颗押入的子弹最后一次才能弹出,遵循了先进后出原则.

image.png

百度百科

java栈的使用

数组模拟栈

思路分析:

  • index 记录当前的位置
  • 添加元素时,每当元素进栈的时候,跟随在上一个元素后面
  • 删除元素时,删除最后一个元素

image.png

栈中是否为空:

只需要判断index是否为第-1个位置即可.

(默认值为-1,如果index = 默认值说明栈中没有数据,说明栈空)

image.png

栈中是否满:

只需要判断index == mMaxSize - 1即可

image.png

出栈

  • index记录的是当前的位置,只需要将index的位置pop出即可

image.png

来看看代码吧:

public class StackList {
    public int mMaxSize;

    //记录最后一个位置
    public int index = -1;

    public int[] stack;

    public StackList(int mMaxSize) {
        this.mMaxSize = mMaxSize;
        stack = new int[mMaxSize];
    }

    //判断栈中是否为空
    public boolean isEmpty() {
        return index == -1;
    }

    //栈是否满
    public boolean isFull() {
        return index == mMaxSize - 1;
    }

    //添加元素
    public void push(int value) {
        if (isFull()) {
            System.out.println("不能添加" + value + ",队列满了");
            return;
        }
        index++;
        stack[index] = value;
    }

    //弹出栈顶元素
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("pop:栈内没有数据");
        }
        int value = stack[index];
        index--;
        return value;
    }

    //打印所有元素
    public void show() {
        if (isEmpty()) {
            System.out.println("show:元素不能为null");
            return;
        }

        for (int i = index ; i >= 0; i--) {
            System.out.println("show元素为:" + stack[i] + "\t下标为:" + i);
        }
    }

    //偷看一下栈顶元素
    public int peek() {
        System.out.println("peek" + stack[index]);
        return stack[index];
    }
}

测试:

public static void main(String[] args) {

        StackList stackList = new StackList(5);
        stackList.push(11);
        stackList.push(22);
        stackList.push(33);
        stackList.push(44);
        stackList.push(55);
//        stackList.push(66);

        try {
            System.out.println("弹出:" + stackList.pop());
            System.out.println("弹出:" + stackList.pop());
            System.out.println("弹出:" + stackList.pop());
            System.out.println("弹出:" + stackList.pop());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        stackList.show();
    }

测试结果为:

弹出:55
弹出:44
弹出:33
弹出:22
show元素为:11	下标为:0

完整代码

完整项目

猜你喜欢:

java数据结构与算法目录

原创不易,您的点赞就是对我最大的支持~