(四)栈—数组模拟栈

1、基本介绍

(四)栈—数组模拟栈_第1张图片

(四)栈—数组模拟栈_第2张图片

2、应用实例(数组模拟栈)

(四)栈—数组模拟栈_第3张图片

package stack;

import java.util.Scanner;

public class ArrayStack {
    public static void main(String[] args) {
        ArrStack stack = new ArrStack(256);
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        char op;
        int val = 0;
        String temp = "";
        while(loop) {
            System.out.println("\n入栈操作(i)");
            System.out.println("出栈操作(o)");
            System.out.println("打印栈栈(p)");
            System.out.println("查看栈是否空(e)");
            System.out.println("查看栈是否满(f)");
            System.out.println("退出程序(q)~");
            System.out.print("请选择你要执行的操作:");
            op = scanner.next().charAt(0);
            switch (op) {
                case 'i':
                    System.out.print("请输入要入栈的元素:");
                    val = scanner.nextInt();
                    stack.push(val);
                    break;
                case 'o':
                    val = stack.pop();
                    System.out.println("出栈元素:" + val);
                    break;
                case 'p':
                    stack.print();
                    break;
                case 'e':
                    temp = !stack.isEmpty() ? "栈不为空!" : "栈为空!";
                    System.out.println(temp);
                    break;
                case 'f':
                   temp = !stack.isFull() ? "栈不为满!" : "栈满!";
                    System.out.println(temp);
                    break;
                default:
                    scanner.close();
                    loop = false;
                    break;
            }
        }
    }

}

class ArrStack{
    private int[] arr;
    private int maxSize;
    private int top;

    public ArrStack(int maxSize) {
        this.maxSize = maxSize;
        top = -1;
        arr = new int[maxSize];
    }

    public void push(int val) {
        if (isFull()) {
            throw new RuntimeException("栈满,入栈失败!");
        }
        arr[++top] = val;
        System.out.println("入栈成功~");
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,出栈失败!");
        }
        return arr[top--];
    }

    public void print() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,出栈失败!");
        }
        System.out.print("栈元素:");
        for (int i = top; i >= 0 ; i--) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

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

    public boolean isFull() {
        if (top == maxSize - 1) {
            return true;
        }
        return false;
    }
}

(四)栈—数组模拟栈_第4张图片

你可能感兴趣的:(数据结构,java,数据结构)