栈的实现及操作
下一部分利用栈做个计算器
package Stack;
import java.util.Scanner;
public class ArrayStackLinkedDemo {
public static void main(String[] args) {
ArrayStackLinked stack = new ArrayStackLinked(4);
String Key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("show:显示栈");
System.out.println("push:入栈");
System.out.println("pop:出栈");
System.out.println("exit:退出");
System.out.println("输入你的选择");
Key = scanner.next();
switch(Key) {
case "show":
stack.liststack();
break;
case "push":
System.out.println("输入一个数");
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int res = stack.pop();
System.out.printf("出栈数据为%d\n",res);
}catch(Exception e) {
System.out.printf(e.getMessage());
}
default:
break;
}
}
}
}
class ArrayStackLinked{
private int top = -1;
private int[]stack;
private int MaxTop;
public ArrayStackLinked(int maxtop) {
this.MaxTop = maxtop;
stack = new int[this.MaxTop];
}
public boolean emptystack() {
return top == -1;
}
public boolean isfullstack() {
return top == MaxTop-1;
}
public void liststack() {
if(emptystack()) {
System.out.println("栈空,无法遍历");
return;
}
for(int i = top;i>=0;i--) {
System.out.printf("stack[%d] = %d\n",i,stack[i]);
}
}
public void push(int value) {
if(isfullstack()) {
System.out.println("栈满,无法入栈");
return;
}
top++;
stack[top] = value;
}
public int pop() {
if(emptystack()) {
throw new RuntimeException("栈空,没有数据");
}
int value = stack[top];
top--;
return value;
}
}
测试
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/61ff9ffabe43ee6d0547f5275513ba07.png#pic_center)