packagecom.hello;importjava.util.*;classStack{privateintar[];privateinttop;Stack(intsize){this.ar=newint[size];this.top=-1;}/**
* Get the top element of the stack.
* You must have to check if stack is empty or not, before calling this API.
* @return {Integer} top of the stack
*/publicinttop(){returnthis.ar[this.top];}/**
* Check if stack is empty or not.
* @return {Boolean} true if stack is empty, false otherwise
*/publicbooleanisEmpty(){returnthis.top==-1;}/**
* Get the size of the stack
* @return {Integer} size of the stack
*/publicintsize(){returnthis.top+1;}/**
* Push el onto the top of the stack
* @param el element to be pushed
*/publicvoidpush(intel){if(this.top+1>=this.ar.length){System.out.println("Stack is full!");return;}// push el into stackthis.ar[++this.top]=el;}/**
* Pop the top element from the stack
*/publicvoidpop(){if(this.top<0){System.out.println("Stack is empty!");return;}this.top--;}}publicclassMethod{publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);System.out.print("Enter stack size: ");intstackSize=sc.nextInt();System.out.println();Stackstack=newStack(stackSize);intop=1;System.out.println("Push: 1");System.out.println("Pop: 2");System.out.println("Top: 3");System.out.println("Size: 4");System.out.println("Exit: 0");while(op!=0){System.out.print("Enter operation number: ");op=sc.nextInt();System.out.println();switch(op){case1:System.out.print("Enter a number: ");intel=sc.nextInt();System.out.println();stack.push(el);break;case2:stack.pop();break;case3:// if stack is empty then don't do pop()if(stack.isEmpty()){System.out.println("Stack is empty!");break;}inttop=stack.top();System.out.println("Top element: "+top);break;case4:intsize=stack.size();System.out.println("Size: "+size);break;}}// close the streamsc.close();}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)