Stack栈的基本操作


package com.qst.test;
import java.util.Scanner;
public class Stack {
    
    
	public static void main(String[] args) {
    
    
		Arraystack sq = new Arraystack(5);
		boolean flag = true;
		String key = "";
		Scanner scanner = new Scanner(System.in);
		while(flag) {
    
    
			System.out.println("show: 表示显示栈");
			System.out.println("exit: 退出程序");
			System.out.println("push: 表示添加数据到栈(入栈)");
			System.out.println("pop: 表示从栈取出数据(出栈)");
			System.out.println("请输入你的选择");
			key = scanner.next();
			switch(key) {
    
    
			case "show":sq.show();break;
			case "exit":scanner.close();flag=false;break;
			case "push":
				System.out.println("请输入一个数");
			int val = scanner.nextInt();	sq.add(val);break;
			case "pop":
				try {
    
    
					int res = sq.out();
					System.out.printf("出栈的数据是 %d\n", res);
				} catch (Exception e) {
    
    
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
				break;
			}
		}
	}
}

class Arraystack {
    
    
	private int maxsize;
	private int[] stack; // 数组,数组模拟栈,数据就放在该数组
	private int top = -1;// top表示栈顶,初始化为-1

	public Arraystack(int num) {
    
    
		maxsize = num;
		stack = new int[maxsize];
	}

	// 栈满
	public boolean isFull() {
    
    
		return top == maxsize - 1;
	}

	// 栈空
	public boolean isEmpty() {
    
    
		return top == -1;
	}

	public void add(int val) {
    
    
		if (isFull()) {
    
    
			System.out.println("已满");
			return;
		}
		top++;
		stack[top] = val;
	}

	public int out() {
    
    
		// 先判断栈是否空
		if (isEmpty()) {
    
    
			// 抛出异常
			throw new RuntimeException("栈空,没有数据~");
		}
		int value = stack[top];
		top--;
		return value;
	}

	public void show() {
    
    
		if (isEmpty()) {
    
    
			System.out.println("没有数据");
			return;
		}
		for (int i = top; i >= 0; i--) {
    
    
			System.out.printf("stack[%d]=%d\n", i, stack[i]);
		}
	}


}

猜你喜欢

转载自blog.csdn.net/weixin_44763595/article/details/106530531
今日推荐