WikiGalaxy

Personalize

Pop Operation on Stack

The pop operation is a fundamental operation of the stack data structure. It involves removing the top element from the stack. Since stacks follow the Last-In-First-Out (LIFO) principle, the last element added to the stack is the first one to be removed.

Example 1: Basic Pop Operation

Consider a stack with elements [A, B, C]. The top of the stack is C. When we perform a pop operation, C is removed.


Stack: [A, B, C] 
Pop Operation -> C is removed
Stack after Pop: [A, B]
            

Example 2: Pop Until Empty

Let's pop all elements from the stack one by one.


Stack: [X, Y, Z]
Pop Operation 1 -> Z is removed
Stack: [X, Y]
Pop Operation 2 -> Y is removed
Stack: [X]
Pop Operation 3 -> X is removed
Stack: []
            

Example 3: Pop from a Single Element Stack

If the stack has only one element, a pop operation will leave the stack empty.


Stack: [P]
Pop Operation -> P is removed
Stack: []
            

Example 4: Pop from an Empty Stack

Attempting to pop from an empty stack typically results in an underflow error.


// Stack is empty
Pop Operation -> Underflow Error
            

Example 5: Pop Operation in a Program

Here is a simple Java program demonstrating the pop operation on a stack.


import java.util.Stack;

public class StackPopExample {
    public static void main(String[] args) {
        Stack stack = new Stack<>();
        stack.push("Apple");
        stack.push("Banana");
        stack.push("Cherry");

        System.out.println("Stack before pop: " + stack);
        String poppedElement = stack.pop();
        System.out.println("Popped element: " + poppedElement);
        System.out.println("Stack after pop: " + stack);
    }
}
            
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025