Stack implementation in java

               Stack is a basic data structure which store the data elements in such a way that LIFO.Stack class is included in java Collections.

The built-in package is: java.util.Stack.

Logic of stack:

  • LIFO (Last in First Out): The number which is inserted as last will be removed first.
  • Dynamic: The size of stack will be increased or decreased depends on the data.

Operations on Stack:

  • push(data) : it is used to add the elements to the stack.
  • pop() : It is used to delete a top most data.
  • peek() : This is used to view the top element of data.
  • search(): It finds a particular data in the stack.
  • empty() :It checks whether stack is empty or not.

Java Implementations on Stack Operations:

              This java program implements a stack and its operations. It has following steps.

Steps:

  • Include the built in java package.
  • A public class is created with main() function.
  • A new stack object is created. 5 elements are inserted into stack using push() function.
  • The stack elements are displayed using print() statement.
  •  peek() function is used to view the top elements without deleting.
  • Pop() function deletes the top element of the stack.
  • Search() method finds an element in the stack.
  • Empty() checks the stack is empty or not.

Program:

import java.util.Stack;

public class StackEg {

    public static void main(String[] args) {

     Stack<Integer> stackobj = new Stack<>();

        // inserting(Pushing) elements

        stackobj.push(100);

        stackobj.push(200);

        stackobj.push(300);

        stackobj.push(400);

        stackobj.push(500);

        // print the stack elements

        System.out.println("Stack : " + stackobj);

        // view the top element(Peek)

        int top1 = stackobj.peek();

        System.out.println("Top element: " + top1);

        // remove the top element in the stack(Pop)

        int popit = stackobj.pop();

        System.out.println("The element which is popped from the stack is: " + popit);

        // printing the stack elements after pop

        System.out.println("Stack after pop: " + stackobj);

        // finding an element

        int pos = stackobj.search(20);

        System.out.println("Position of element: " + pos);

        // finding the stack is empty or not.

        boolean isEmpty = stackobj.empty();

        System.out.println("stack empty " + isEmpty);

    }

}

Output:

C:\raji\blog>javac StackEg.java

C:\raji\blog>java StackEg

Stack : [100, 200, 300, 400, 500]

Top element: 500

The element which is popped from the stack is: 500

Stack after pop: [100, 200, 300, 400]

Position of element: -1

stack empty false

Note: Stack is useful when backtracking is needed and process the elements in last in first out order.

No comments:

Post a Comment