五、数据结构与算法 (一)栈的数组实现

2022/3/19 20:28:42

本文主要是介绍五、数据结构与算法 (一)栈的数组实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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.



这篇关于五、数据结构与算法 (一)栈的数组实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程