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.
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:
After performing these steps, the stack will have the following structure:
Stack (Top -> Bottom):
Top -> 4 -> 3 -> 2 -> 1
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
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.