数据结构 - 栈(数组模拟栈操作)

数据结构 - 栈(数组模拟栈操作)_第1张图片

数组模拟栈操作

package stack;

import java.util.Scanner;

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

        while (loop){
            System.out.println("show:表示显示栈");
            System.out.println("exit:退出程序");
            System.out.println("push:表示入栈");
            System.out.println("pop:表示出栈");
            key = sc.next();
            switch (key){
                case "show":
                    arrayStack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数");
                    int value = sc.nextInt();
                    arrayStack.push(value);
                    break;
                case "pop":
                    try{
                        System.out.println("出栈的数据是:"+arrayStack.pop());
                    }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; //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;
    }

    // 入栈 push
    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 stack[value];
    }

    //遍历栈(从栈顶开始)
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
        }
        for (int i = top; i>=0; i--){
            System.out.printf("stack[%d] = %d\n",i,stack[i]);
        }
    }
}

你可能感兴趣的:(数据结构与算法,数据结构,栈,数组模拟栈)