顺序栈示意图:
顺序栈的特点:先进后出,栈顶进栈顶出。
1. 顺序栈的创建
public Stack(){
this(10);
}
public Stack(int size){
this.elem=new int[size];//顺序栈的大小
int top=0;
}
```2. 判断栈是否为满
<div class="se-preview-section-delimiter"></div>
这里写代码片
“`
- 入栈
- 判断栈是否为空
- 出栈
public boolean isFull(){
if(this.top==this.elem.length){//top等于顺序栈的
//长度
return true;
}
return false;
}
- 入栈
public boolean push(int val){
//如果return true或return false 此方法为布尔类型
if(isFull()){//判断顺序栈是否已满
return false;
}
this.elem[this.top++]=val;//将元素放入top位置
return true;
}
试图分析:
4. 判断栈是否为空
public boolean isEmpty(){
if(this.top==0){
return true;
}
return false;
}
- 出栈
public void pop(){
if(isEmpty()){//判断栈是否为空
return;
}
--this.top;//top值减一
}
视图分析:
6、得到栈顶元素
//得到栈顶元素
public int getTop(){
if(isEmpty()){
return -1;
}
return this.elem[this.top-1];//不能进行
//--this.top 不能改变top的值
}
7、打印栈内函数
public void show(){
for(int i=0;i<this.top;i++){//遍历栈
System.out.print(this.elem[i]+" ");
}
System.out.println();
}