Implementation of Stack

import java.util.Scanner;
class myStack{
               
                private int top;
                private int item[];
                private int stackSize;
               
                myStack(int size){
                                stackSize=size;
                                top=-1;
                                item=new int[stackSize];
                }
                public boolean isFull(){
               
                                return (top==stackSize-1);
                }
               
                public boolean isEmpty(){
                                return (top==-1);
                }
                public void push(int x){
                                item[++top]=x;
                }
                public int pop(){
                                return item[top--];
                               
                }
               
                public static void main(String[] a){
                                System.out.print("How many numbers of item to push in to the stack :");
                                Scanner sc=new Scanner(System.in);
                                int size=sc.nextInt();
                                myStack stack=new myStack(size);
                                System.out.println();
                                System.out.println("Size of the stack is :"+size);
                                while(!stack.isFull()){
                                                System.out.print("Enter an element to push to stack :");
                                                int k=sc.nextInt();
                                                stack.push(k);
                                                System.out.println();
                                }
                                while(!stack.isEmpty()){
                                                int ip=stack.pop();
                                                System.out.println("Item popped: "+ip);
                                }
                }
}




No comments:

Post a Comment