Stack Program in Java



Java Implementation

Following is the implementation of basic operations (push(), pop(), peek(), isEmpty(), isFull()) in Stack ADT and printing the output in JAVA programming language −

import java.io.*;
import java.util.*; // util imports the stack class
public class StackExample {
   public static void main (String[] args) {
      Stack<Integer> stk = new Stack<Integer>();
      
      // inserting elements into the stack
      stk.push(52);
      stk.push(19);
      stk.push(33);
      stk.push(14);
      stk.push(6);
      System.out.print("The stack is: " + stk);
      
      // deletion from the stack
      System.out.print("\nThe popped element is: ");
      Integer n = (Integer) stk.pop();
      System.out.print(n);
      
      // searching for an element in the stack
      Integer pos = (Integer) stk.search(19);
      if(pos == -1)
         System.out.print("\nThe element 19 not found in stack");
      else
         System.out.print("\nThe element 19 is found at " + pos);
   }
}

Output

The stack is: [52, 19, 33, 14, 6]
The popped element is: 6
The element 19 is found at 3
Advertisements