栈的介绍
栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
入栈图解
出栈图解
代码实现
/** * All rights Reserved, Designed By https://www.tulingxueyuan.com/ * @Title: ArrayStack.java * @Package com.tuling.infix * @Description: * @author 北京图灵学院 * @date 2019年11月21日 * @version V1.0 */ package com.tuling.infix; /** * @ClassName: ArrayStack * @Description: * @author 小白 * @date 2019年11月21日 * */ public class ArrayStack { private int[] stack; private int count; private int top; /** * 创建一个新的实例 ArrayStack. * */ public ArrayStack() { this(10); } /** * 创建一个新的实例 ArrayStack. * * @param count */ public ArrayStack(int count) { this.count = count; stack = new int[count]; top = -1; } /** * * @Title: push * @Description:入栈 * @param data * @return void * @throws */ public void push(int data) { if(isFull()) { throw new IllegalArgumentException("栈溢出!"); } stack[++top] = data; } /** * * @Title: show * @Description:显示栈内的所有数据 * @param * @return void * @throws */ public void show() { if(isEmpty()) { throw new IllegalArgumentException("栈为空!"); } //从栈顶开始展示 for(int i = top; i >= 0; i--) { System.out.print(stack[i] + " "); } System.out.println(); } /** * * @Title: pop * @Description:弹栈 * @param * @return int * @throws */ public int pop() { if(isEmpty()) { throw new IllegalArgumentException("栈为空!"); } return stack[top--]; } /** * * @Title: isFull * @Description:判断栈是否已满 * @param * @return boolean * @throws */ public boolean isFull() { return top == (count-1); } /** * * @Title: isEmpty * @Description:判断栈是否为空 * @param * @return boolean * @throws */ public boolean isEmpty() { return top == -1; } /** * @return stack */ public int[] getStack() { return stack; } /** * @param stack the stack to set */ public void setStack(int[] stack) { this.stack = stack; } /** * @return count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } /** * @return top */ public int getTop() { return top; } /** * @param top the top to set */ public void setTop(int top) { this.top = top; } }
测试
/** * All rights Reserved, Designed By https://www.tulingxueyuan.com/ * @Title: StackDemo.java * @Package com.tuling.infix * @Description: * @author 北京图灵学院 * @date 2019年11月21日 * @version V1.0 */ package com.tuling.infix; /** * @ClassName: StackDemo * @Description: * @author 小白 * @date 2019年11月21日 * */ public class StackDemo { /** * @Title: main * @Description: * @param @param args * @return void * @throws */ public static void main(String[] args) { ArrayStack as = new ArrayStack(5); //压栈 as.push(4); as.push(26); as.push(8); as.push(30); as.push(10); // as.push(2); //打印栈内数据 as.show(); System.out.println("-----------弹栈操作--------------"); //弹栈 System.out.println(as.pop() + " 弹栈"); as.show(); System.out.println(as.pop() + " 弹栈"); as.show(); } }
运行结果:
还没有评论,来说两句吧...