栈:栈是限定仅在表尾进行插入和删除操作的线性表。“栈”者,存储货物或供旅客住宿的地方,可引申为仓库、中转站,引入到计算机领域里,就是指数据暂时存储的地方,所以才有进栈、出栈的说法
实现一个简单的栈:1,先定义栈的容量
2,定义栈顶,为-1
3,定义一个存储数据的数组stackArray[ ]
代码:
package Stack;
public class StackDemo {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.list();
}
}
class Stack{
int stackArray[];
int maxSize;//栈容量
int top = -1;//栈顶
public Stack(int maxSize) {
this.maxSize = maxSize;
stackArray = 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++;
stackArray[top] = value;
}
//出栈
public int pop(){
if (isFull()){
throw new RuntimeException("栈空");
} //临时变量保存栈顶元素
int value = stackArray[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,stackArray[i]);
}
}
}