首先,我们了解到栈他是一个线性结构, 他有栈顶,栈底,出栈,弹栈,并且仅能从栈顶进行出栈和弹栈操作,所以他的特点是先进后出。
基础语言(JAVA)
实现思路(出栈,弹栈,栈顶,一个数组)
准备一个栈顶默认值是-1,表示是空栈的意思
//栈顶 private int top = -1;
准备一个数组
//数组 private int[] stack;
构造方法初始化数组
public ArrayStack(int stackLength){ this.stackLength = stackLength; this.stack = new int[this.stackLength]; }
判断满栈和空栈的操作(满栈肯定就是数组长度-1,空栈就是默认的-1)
//是否满栈 public boolean isFull(){ return this.top == stackLength - 1; }
//是否空栈 public boolean isEmpty(){ return this.top == -1; }
进行入栈和弹栈的操作
//压栈 public void push(int val){ if (isFull()){ throw new RuntimeException("栈已满"); } this.top++; this.stack[top] = val; } //弹栈 public int pop(){ if (isEmpty()){ throw new RuntimeException("栈空"); } int val = this.stack[this.top]; this.top--; return val; }
入栈先判是否满栈, 弹栈先判是否空栈
public static void main(String[] args) { ArrayStack arrayStack = new ArrayStack(5); Random random = new Random(); for (int i = 0; i < 5; i++) { arrayStack.push(random.nextInt(10)); } arrayStack.list(); System.out.println(arrayStack.pop()); }
最终得到了 结果 如果有误请各位指正,互相进步