Stack Peek Operation



Peek Element at Top of Stack

The peek operation in a stack involves viewing the element at the top of the stack without removing it. This operation allows us to access the top element while keeping the stack intact. Stacks follow a Last In, First Out (LIFO) principle, meaning the most recently added element is at the top of the stack.


Step-by-Step Process

Consider a stack with the following structure before the peek operation:


Stack (Top -> Bottom):
Top -> 4 -> 3 -> 2 -> 1

To peek the top element of the stack, follow these steps:

  1. Check if the Stack is Empty: If the stack is empty, return an error or None.
  2. Return the Top Node's Value: Return the value of the top node.

After performing these steps, the stack remains unchanged:


Stack (Top -> Bottom):
Top -> 4 -> 3 -> 2 -> 1

Pseudo Code

Function peek(stack):
    # Check if the stack is empty
    If stack.top is null:
        Return None
    # Return the value of the top node
    Return stack.top.data

Python Program to Perform Stack Peek Operation

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 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()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
print("Stack before peeking:")
stack.traverse()  # Output: 4 -> 3 -> 2 -> 1 -> None
peeked_element = stack.peek()
print(f"Peeked element: {peeked_element}")  # Output: 4
print("Stack after peeking:")
stack.traverse()  # Output: 4 -> 3 -> 2 -> 1 -> None

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, and traversing the stack. The peek method checks if the stack is empty and returns the value of the top node without modifying the stack.