Check if Stack is Empty



Check if Stack is Empty

The operation to check if a stack is empty involves verifying whether the stack contains any elements. This operation is useful to determine if the stack has any elements before performing operations like pop or peek. A stack is considered empty if its top reference is None.


Step-by-Step Process

To check if a stack is empty, follow these steps:

  1. Check the Top Reference: Verify if the top reference of the stack is None.
  2. Return Result: Return True if the top reference is None, indicating the stack is empty. Otherwise, return False.

Pseudo Code

Function is_empty(stack):
    # Check if the top reference is None
    If stack.top is null:
        Return True
    # Otherwise, return False
    Return False

Python Program to Check if Stack is Empty

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Stack:
    def __init__(self):
        self.top = None

    def push(self, data):
        # Create a new node with the given data
        new_node = Node(data)
        # Set the new node's next reference to the current top of the stack
        new_node.next = self.top
        # Update the top reference to the new node
        self.top = new_node

    def pop(self):
        # Check if the stack is empty
        if self.top is None:
            return None
        # Store the current top node
        temp = self.top
        # Update the top reference to the next node
        self.top = self.top.next
        # Return the value of the stored top node
        return temp.data

    def peek(self):
        # Check if the stack is empty
        if self.top is None:
            return None
        # Return the value of the top node
        return self.top.data

    def is_empty(self):
        # Check if the top reference is None
        return self.top is None

    def traverse(self):
        # Traverse and print the stack
        current = self.top
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

# Example usage:
stack = Stack()
print("Is stack empty?", stack.is_empty())  # Output: True
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack after pushing 3 elements:")
stack.traverse()  # Output: 3 -> 2 -> 1 -> None
print("Is stack empty?", stack.is_empty())  # Output: False
stack.pop()
stack.pop()
stack.pop()
print("Stack after popping all elements:")
stack.traverse()  # Output: None
print("Is stack empty?", stack.is_empty())  # Output: True

This Python program defines a stack with methods for pushing elements onto the stack, popping elements from the stack, peeking at the top element of the stack, checking if the stack is empty, and traversing the stack. The is_empty method checks if the top reference is None and returns True if the stack is empty, otherwise returns False.