Java language uses array to implement stack

class Stack{
private int maxSize;
private long[] stackArray;
private int top;//Record the subscript of the top of the stack public Stack(int s) { maxSize=s; stackArray=new long[maxSize];//Create an array top= -1;//The initial stack top is -1, the array cannot be accessed } public void push(long j) {// Push stackArray[++top]=j;//Push data into the stack } public long pop () {//Pop stack, no parameters, LIFO return stackArray[top--]; } public long peek() {//View stack top element return stackArray[top]; } public boolean isEmpty() {// Judging whether the stack is empty return (top==-1); } public boolean isfull() {//Judging whether the stack is full return (top==maxSize-1); }



























}




public class Array implementation of stack {
public static void main(String[] args) {
Stack theStack=new Stack(10);//Create a stack that can hold 10 data items
theStack.push(1);
theStack.push (2);
theStack.push(3);
theStack.push(4); while(!theStack.isEmpty()) {//Output the elements in the stack, last in first out, until the stack is judged to be empty and stop long value =theStack. pop(); System.out.print(value+" "); } } }







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325371732&siteId=291194637