栈是一种数据的存储机制,只能在一端进行插入和取出操作,具有先进后出的特点。
栈数据结构中心思想
栈有两个要素, 栈底和栈顶。数据入栈时,栈顶升高。数据出栈时,栈顶下降。而栈底是保持不变的。当栈顶与栈底重合时,则这个栈为空栈。//定义一个栈的类
class Stack{
int top; //栈顶
int size; //栈的最大容量
Object[] p; //栈空间的指针,根据不同的需要申请不同的数据存储空间,这里是基类类型的
//创建一个栈
public Stack(int size){
//申请指定大小的栈空间
this.top = 0;
this.size = size;
this.p = new Object[size];
};
//判空栈
public boolean StackEmpty(){
if(0 == this.top){
return true;
}
return false;
}
//判满栈
public boolean StackFull(){
if(this.size == this.top){
return true;
}
return false;
}
//清空栈
public void ClearStack(){
this.top = 0;
}
//元素入栈
public boolean Push(Object elem){
//入栈前先判断栈是否为满
if(this.StackFull()){
return false;
}
this.p[this.top] = elem;
this.top++;//栈顶上浮
return true;
}
//元素出栈
public boolean Pop(Object elem){
//出栈前先判断栈内是否有元素
if(this.StackEmpty()){
return false;
}
elem = this.p[this.top-1];
this.top--;//栈顶下降
return true;
}
//遍历栈
public void Traverse(){
//从栈底开始遍历
for(int i = 0 ; i < this.top ; i++){
System.out.print(this.p[i] + ",");
}
//从栈顶开始遍历
for(int j = this.top-1 ; j >= 0 ; j--){
System.out.print(this.p[j] + ",");
}
}