实现栈的思路:
1.使用数组来模拟栈;
2.定义一个top来表示栈顶,初始化为-1;
3.入栈:当有数据(data)加入(push)到栈时:top++,stack[top] = data;
4.出栈: int value = stack[top]; top–; return value;
代码:
//自己写的栈
public class MyselArraysStack {
/*
实现栈的思路:
1.使用数组来模拟栈;
2.定义一个top来表示栈顶,初始化为-1;
3.入栈:当有数据(data)加入(push)到栈时:top++,stack[top] = data;
4.出栈: int value = stack[top]; top--; return value;
*/
private int maxSize; // 栈的最大大小;
private int[] stack; //数组模拟栈,数据就放在数组中.
private int top = -1; //top表示栈顶,初始化为-1;
//构造器
public MyselArraysStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//判断栈满:当 top == maxSize-1 时栈满
public boolean isFull() {
return top == maxSize - 1;
}
//判断栈空:当 top == -1 时栈空
public boolean isEmpty() {
return top == -1;
}
//入栈(push)
public void push(int value) {
//如果栈已经满的话,无法push.
if (isFull()) {
System.out.println("栈满,无法加入");
return;
} else {
top++;
stack[top] = value;
}
}
//出栈(pop)j将栈顶的元素返回
public int pop() {
//先判断栈是否为空
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据");
} else {
int value = stack[top];
top--;
return value;
}
}
//显示栈的情况(遍历栈)
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据!");
} else {
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
//演示模拟栈
public static void main(String[] args) {
MyselArraysStack myselArraysStack = new MyselArraysStack(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":
myselArraysStack.list();
break;
case "push":
System.out.println("请输入一个数:");
int value = scanner.nextInt();
myselArraysStack.push(value);
break;
case "pop":
try {
int res = myselArraysStack.pop();
System.out.println("出栈的数据:" + res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}