栈的特点即先进后出,采用数组模拟栈,实现栈的这一特性主要是靠定义一个指针(索引).
指针的初始位置指向的是-1
以下给出代码:
package com.ebiz.stack;/*** @author YHj* @create 2019-07-20 14:20* 数组模拟栈*/public class ArrayStack {private int maxSize;private int [] arr; //数组模拟栈private int top = -1;//构造方法,初始化数组public ArrayStack(int maxSize) {this.maxSize=maxSize;this.arr = new int[maxSize];}//验证栈满public boolean isFull(){return top == maxSize-1;}//验证为空public boolean isEmpty(){return top == -1;}//入栈public void push(int value){if (isFull()){System.out.println("栈已满");return;}top++;arr[top]=value;}//出栈public int pop(){if(isEmpty()){throw new RuntimeException("栈已空");}int value=arr[top];top--;return value;}//遍历栈public void list(){if (isEmpty()){throw new RuntimeException("栈为空");}while (true){if (isEmpty()){System.out.println("栈为空");break;}System.out.printf("出站元素为%d%n",arr[top]);top--;}} }
数组模拟栈,给出了pop,push,list几个简单方法,下面给出测试类,
package com.ebiz.stack;/*** @author YHj* @create 2019-07-20 15:11*/ public class Test {public static void main(String[] args) {//初始化栈ArrayStack stack = new ArrayStack(5);//添加元素for (int i = 1; i <=5 ; i++) {stack.push(i);}//获取栈顶 System.out.println(stack.pop());System.out.println(stack.pop());//遍历栈 stack.list();} }