1.栈定义
栈也是一种线性结构,但是是一种受限的线性表,它只能在栈顶进行操作,栈底不能进行操作。
通常栈的操作有 构建空栈,入栈,出栈,判断是否空栈,获取栈顶元素等等
2.栈的分类
栈是线性表,按照栈的物理存储方式可以分为顺序栈和链式的栈。顺序栈基本是用数组来实现,链式栈通常通过链表来实现
3.顺序栈
public class MyStack {
private int[] table;
private int top;
public MyStack(int initSize){
this.table = new int[initSize];
this.top = -1;
}
public boolean push(int element){
if(top + 1 >= table.length){
throw new RuntimeException("stack over flow");
}
table[top + 1] = element;
top = top + 1;
return true;
}
public int pop(){
if(top == -1){
throw new RuntimeException("stack is empty");
}
int element = table[top];
top = top -1;
return element;
}
public boolean clearStack(){
top = -1;
return true;
}
public boolean isEmpty(){
return top == -1;
}
}