用数组实现栈,设置三个属性
1、maxSize 用来记录这个数组实现的栈能存放多少个数据
2、long[] stackArray 定义一个数组栈
2、long[] stackArray 定义一个数组栈
3、top 记录栈顶
方法有
1、有参构造函数,创建一个栈,参数是栈的大小
2、push方法,压入一个数字
2、push方法,压入一个数字
3、pop方法,弹出栈顶的一个数字
4、peek方法,查看栈顶的数字
5、isEmpty(),isFull()判断是不是空的栈和栈满了没有
/** * Description:用数组实现栈 * @author 李弘昊2019年10月29日 */ class StackX { private int maxSize; //size of stack array private long[] stackArray; private int top; //top of stack public StackX(int s) //constructor { maxSize = s; stackArray = new long[maxSize]; //create array top = -1; //no items yet } public void push(long j) //put item on top of stack { stackArray[++top] = j; //increment top,insert item } public long pop() //take item from top of stack { return stackArray[top--];//access items,decrement top } public long peek() //peek at top of stack { return stackArray[top]; } public boolean isEmpty() //true if stack is empty { return(top == -1); } public boolean ifFull() //true if stack is full { return(top == maxSize-1); } } public class StackApp { public static void main(String[] args) { StackX theStack = new StackX(10); //make new stack theStack.push(20); //push items onto stack theStack.push(40); theStack.push(60); theStack.push(80); System.out.println("the top value:"+theStack.peek()); while(!theStack.isEmpty()) //until it'empty { System.out.print(theStack.pop()); System.out.print(" "); } } }