目录
项目简述:
项目用到的图片/gitee地址
项目代码:
ArrayStack栈类
出栈方法pop
入栈的方法push
遍历栈的方法list()
测试以上的功能用main()
项目简述:
1.用数组的形式来模拟栈,入栈后的元素依然保存在数组中,无法真正的删除,但是用链表模拟栈时出栈就可以删除掉元素。
2.定义的stact类(栈类):最大尺寸、数组、栈顶指针初始化为-1。
3.实现起来很简单,不难。
项目用到的图片/gitee地址
Stack文件夹
项目代码:
ArrayStack栈类
注:maxSize:栈的最大容量,stack存放元素的数组,top栈顶指针。该代码块为所有的代码,下面有单独的讲解。
class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
//构造函数
public ArrayStack(int maxSize){
this.maxSize = maxSize;
this.stack = new int[this.maxSize];
}
public boolean isFull(){
if(top == maxSize -1 ){
return true;
}else {
return false;
}
}
public boolean isEmpty(){
if(top == -1){
return true;
}else {
return false;
}
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
int res = stack[top];
top--;
return res;
}
public void push(int num){
if(isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = num;
}
public void list(){
if (isEmpty()){
System.out.println("栈空");
return;
}
for (int i = top;i>= 0;i--){
System.out.printf("stact[%d]=%dn",i,stack[i]);
}
}
}
出栈方法pop
注解: 记得出栈前先判断是否为空
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
int res = stack[top];
top--;
return res;
}
入栈的方法push
注:判断是否栈满
public void push(int num){
if(isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = num;
}
遍历栈的方法list()
注:先判断是否为空
public void list(){
if (isEmpty()){
System.out.println("栈空");
return;
}
for (int i = top;i>= 0;i--){
System.out.printf("stact[%d]=%dn",i,stack[i]);
}
}


![数组实现栈---[java版] 数组实现栈---[java版]](http://www.mshxw.com/aiimages/31/396763.png)
