原理简介:
首先有一个空数组arr,定义一个变量top,赋初始值为-1,此时位于栈底;
每次add()添加元素时候,只需要++top,并把值给arr[top],即top指针先向上移动一位,再赋值;
另外,模拟pop()元素出栈的过程。举例,如果现在有4个元素,即top到了索引3的位置,为了遵循先进后出的原则,可以直接打印出arr[ top ],打印完之后让top-1,就完成了。
再加两个辅助方法,入栈的时候要判断栈是否满,以及出栈的时候判断栈是否为空。
class MyStack{
int arr[];
int top;
int maxSize;
public MyStack(int size){
this.maxSize = size;
arr = new int[maxSize];
}
public void push(int value){
if(isFull()) {
System.out.println("Stack is Full!");
return;
}
arr[++top] = value;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("this stack is empty");
}
int data = arr[top--];
return data;
}
public boolean isFull() {
return top == maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
}