1.功能
利用数组实现栈的基本操作
2.代码实现
1.栈
package ArrayStack;
import java.lang.reflect.Array;
public class Stack {
private int maxSize;
private int[] Stack;
private int top = -1;
public Stack(int maxSize) {
this.maxSize = maxSize;
Stack = new int[this.maxSize];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public void push(int elementPop) {
if (isFull()) {
System.out.println("栈已满,不能再入栈");
}
top++;
Stack[top] = elementPop;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
int value = Stack[top];
top--;
return value;
}
public void showStack() {
if (isEmpty()) {
System.out.println("栈空,没有数据");
}
for (int i = top; i >= 0; i--) {
System.out.printf("Stack[%d]=%d\n", i, Stack[i]);
}
}
}
2.入口
package ArrayStack;
import org.w3c.dom.ls.LSOutput;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack stack = new Stack(4);
String str = "";
boolean flag = true;
while (flag) {
System.out.println("show ----------显示栈");
System.out.println("pop -----------出栈(删除元素)");
System.out.println("push -----------进栈(添加元素)");
System.out.println("exit------------退出程序");
System.out.println("请输入您的选择:");
str = scanner.next();
switch (str) {
case "show":
stack.showStack();
break;
case "pop":
try {
int res = stack.pop();
System.out.printf("出栈元素是:%d", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "push":
System.out.println("请输入要入栈的元素:");
int num = scanner.nextInt();
stack.push(num);
break;
case "exit":
scanner.close();
flag = false;
break;
default:
break;
}
}
}
}