Stack Push Operation


Push Element to Stack

The push operation in a stack involves adding an element to the top of the stack. This operation increases the size of the stack by one and updates the top reference to the new element. Stacks follow a Last In, First Out (LIFO) principle, meaning the most recently added element is the first to be removed.


Step-by-Step Process

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


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

To push an element with the value 4 onto the stack, follow these steps:

  1. Create a New Node: Create a new node with the desired value (4).
  2. Set the New Node's Next Reference: Update the next reference of the new node to point to the current top of the stack.
  3. Update the Top Reference: Update the top reference to point to the new node.

After performing these steps, the stack will have the following structure:


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

Pseudo Code

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

Python Program to Perform Stack Push 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 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)
print("Stack after pushing 3 elements:")
stack.traverse()  # Output: 3 -> 2 -> 1 -> None
stack.push(4)
print("Stack after pushing another element (4):")
stack.traverse()  # Output: 4 -> 3 -> 2 -> 1 -> None

This Python program defines a stack with methods for pushing elements onto the stack and traversing the stack. The push method creates a new node, sets its next reference to the current top of the stack, and updates the top reference to the new node.