一:图形分析
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190927105556143.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDEwNDA5OQ==,size_16,color_FFFFFF,t_70)
二:思路分析
1. 定义一个top来表示入栈的数量(栈顶),当添加一个数据时top会指向新添加的数据;
2. 设置top = -1;(初始值)默认栈为空,当 top == stack.size() 时表示栈满;
3. 定义一个数组 stack 模拟栈,保存需要入栈的值;
4. 入栈:接收一个值,将值保存到 stack 中,并将 top 的位置上移 ;
5. 出栈:将栈顶top的值取出,并将top下移,重新标记栈顶的位置;
三:实现代码
class ArrayStack {
private int maxSize;
private int[] stack;
private int 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.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}