Apr 4, 2011

Stack Implementation in Java

 import java.util.*;  
 class stack_operations  
 {  
      private int size;  
      private int stack[];  
      private int top;  
      stack_operations(int s)  
      {  
           size=s;  
           stack=new int [size];  
           top=-1;  
      }  
      public void push (int item)  
      {  
           stack[++top]=item;  
      }  
      public int pop()  
      {  
           return stack[top--];  
      }  
      public int peek()  
      {  
           return stack[top];  
      }  
      public boolean isFull()  
      {  
           return (top==size-1);  
      }  
      public boolean isEmpty()  
      {  
           return (top==-1);  
      }  
      public void display()  
      {  
           for (int i=0;i<=top ;i++ )  
           {  
                System.out.print(""+stack[i]+"     ");  
           }  
           System.out.println();  
      }  
 }  
 class stack   
 {  
      public static void main(String[] args)   
      {  
           Scanner scan=new Scanner(System.in);  
           System.out.print("Size of the stack?? :");  
           int size=scan.nextInt();  
           stack_operations obj=new stack_operations(size);  
           while (true)  
           {  
                System.out.println("1.Insert\n2.Pop\n3.IsEmpty\n4.isFull.\n5.display\n6.exit");  
                System.out.println("Enter your option:");  
                int option=scan.nextInt();  
                switch (option)  
                {  
                     case 1:  
                          System.out.print("Enter element:");  
                          int item=scan.nextInt();  
                          if (!obj.isFull())  
                          {  
                               obj.push(item);  
                               System.out.println("Inserted successfully.");  
                          }  
                          else  
                               System.out.println("Not able to Insert");                           
                          break;  
                     case 2:  
                          obj.pop();  
                       break;  
                     case 3:  
                          obj.isFull();  
                          break;  
                     case 4:  
                          obj.isEmpty();  
                          break;  
                     case 5:  
                          obj.display();  
                          break;  
                     case 6:  
                          System.exit(0);  
                     default:  
                          System.out.println("Wrong input.");  
                }  
           }  
           //System.out.println("Hello World!");  
      }  
 }  

No comments:

Post a Comment