对于栈来说,只有入栈和出栈操作,所以只需要一个栈顶指针即可。另外需要初始化数组的大小和数据存放的空间。代码如下:
public class ArrayStack {
private int maxSize;
private int[] stack;
private int top = -1; // 栈指向栈顶元素,初始化为空
public ArrayStack(int maxSize){
this.maxSize = maxSize;
this.stack = new int[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]);
}
}
}
测试代码:
public class Test {
public static void main(String[] args){
// 栈 ---- 数组
ArrayStack arrayStack = new ArrayStack(10);
arrayStack.push(1);
System.out.println(arrayStack.pop());
System.out.println(arrayStack.pop());
}
}