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

韩顺平数据结构用数组模拟栈笔记

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

韩顺平数据结构用数组模拟栈笔记

主要体现的是栈先进后出的特点

代码实现:

package Stack;

import java.util.Scanner;


public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试ArrayStack
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        Scanner sc = new Scanner(System.in);
        boolean loop = true;

        while(loop){
            System.out.println("show: 表示显示栈");
            System.out.println("exit: 退出程序");
            System.out.println("push: 表示添加数据到栈(入栈)");
            System.out.println("pop: 表示从栈取出数据(出栈)");
            System.out.println("请输入你的选择");
            key = sc.next();
            switch (key){
                case "show":
                    stack.List();
                    break;
                case "push":
                    System.out.println("请输入一个数:");
                    int value = sc.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try{
                        int result = stack.pop();
                        System.out.printf("出栈的顺序是:%d",result);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    sc.close();
                    loop = false;//退出循环
                    break;
            }
        }
        System.out.println("退出程序");
    }
}

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

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[this.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];
        top--;
        return value;
    }

    //显示遍历栈
    public void List(){
        if (isEmpty()){
            System.out.println("栈空,无法显示数据");
            return;
        }

        for (int i = top; i >= 0; i--){
            System.out.printf("stack[%d] = %dn",i,stack[i]);
        }
    }
}

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

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

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