栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数组实现栈---[java版]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数组实现栈---[java版]

目录

项目简述:

项目用到的图片/gitee地址

项目代码:

ArrayStack栈类

出栈方法pop

入栈的方法push

遍历栈的方法list()

测试以上的功能用main()


项目简述:

1.用数组的形式来模拟栈,入栈后的元素依然保存在数组中,无法真正的删除,但是用链表模拟栈时出栈就可以删除掉元素。

2.定义的stact类(栈类):最大尺寸、数组、栈顶指针初始化为-1。

3.实现起来很简单,不难。


项目用到的图片/gitee地址

Stack文件夹


项目代码:

ArrayStack栈类

注:maxSize:栈的最大容量,stack存放元素的数组,top栈顶指针。该代码块为所有的代码,下面有单独的讲解。

class ArrayStack{
    private int maxSize;
    private int[] stack;
    private int top = -1;

    //构造函数
    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }
    
    public boolean isFull(){
        if(top == maxSize -1 ){
            return true;
        }else {
            return false;
        }
    }

    
    public boolean isEmpty(){
        if(top == -1){
            return true;
        }else {
            return false;
        }
    }

    
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈为空!");
        }
        int res = stack[top];
        top--;
        return res;

    }
    
    public void push(int num){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = num;
    }

    
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        for (int i = top;i>= 0;i--){
            System.out.printf("stact[%d]=%dn",i,stack[i]);
        }
    }
}

出栈方法pop

注解: 记得出栈前先判断是否为空

    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈为空!");
        }
        int res = stack[top];
        top--;
        return res;

    }

入栈的方法push

注:判断是否栈满

 
    public void push(int num){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = num;
    }


遍历栈的方法list()

注:先判断是否为空

 
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        for (int i = top;i>= 0;i--){
            System.out.printf("stact[%d]=%dn",i,stack[i]);
        }
    }

测试以上的功能用main()
public class stack {

    public static void main(String[] str){
        //测试栈的功能
        ArrayStack stack = new ArrayStack(5);
        //给栈赋值
        for (int i = 0;i<5;i++){
            stack.push(i);
        }
        //测试出栈与入栈
        stack.push(5);
        stack.list();
        System.out.println("---------------");
        int res1 = stack.pop();
        System.out.println(res1);
        stack.list();
        System.out.println("---------------");
        int res2 = stack.pop();
        System.out.println(res2);
        stack.list();

    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/396763.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号