数组模拟栈
package com.pro.stack;
public class ArrayStack {
private int maxSize;//栈的大小
private int[] stack;//数组,数组模拟栈,数据就放在该数组中
private int top=-1;//top表示栈顶,初始化为-1
//构造
public ArrayStack(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.println("stack["+i+"]="+stack[i]);
}
}
}
package com.pro.stack;
import java.util.Scanner;
import java.util.Stack;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack arrayStack=new ArrayStack(5);
char key = ' ';// 接受用户输入
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show):显示栈");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到栈");
System.out.println("g(get):从栈取出数据");
key = scanner.next().charAt(0);// 接受一个数据
switch (key) {
case 's':
arrayStack.list();
break;
case 'a':
System.out.println("输入一个数:");
int value=scanner.nextInt();
arrayStack.push(value);
break;
case 'g':
try {
int res=arrayStack.pop();
System.out.println("取得的数据为:"+res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}