数组模拟栈
今天用java实现了用数组模拟栈的操作,如有错误之处,还望指出,我会及时改正。
package com.stack;
import java.util.Scanner;
public class ArrayStackDemo1 {
public static void main(String[] args) {
ArrayStack1 stack = new ArrayStack1(4);
String key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while (loop) {
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":
stack.list();
break;
case "exit":
scanner.close();
loop=false;
break;
case "push":
System.out.println("请输入数据:");
int data=scanner.nextInt();
stack.push(data);
break;
case "pop":
try {
int value = stack.pop();
System.out.println(value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
//定义一个类,表示栈
class ArrayStack1 {
private int maxSize;// 栈的大小
private int[] stack;// 数组模拟栈,数据就放在该数组中
private int top = -1;// 表示栈顶,初始化为-1
// 构造器
public ArrayStack1(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]=%d\n", i, stack[i]);
}
}
}