项目简述:
项目用到的图片/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]); } }
测试以上的功能用main()
public class stack { public static void main(String[] str){ //测试栈的功能 ArrayStack stack = new ArrayStack(5); //给栈赋值 for (int i = 0;i<5;i++){ stack.push(i); } //测试出栈与入栈 stack.push(5); stack.list(); System.out.println("---------------"); int res1 = stack.pop(); System.out.println(res1); stack.list(); System.out.println("---------------"); int res2 = stack.pop(); System.out.println(res2); stack.list(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)