Stack Pop Operation
Pop Element from Stack
The pop operation in a stack involves removing the element from the top of the stack. This operation decreases the size of the stack by one and updates the top reference to the next element in the stack. 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 pop operation:
Stack (Top -> Bottom):
Top -> 4 -> 3 -> 2 -> 1
To pop the top element from the stack, follow these steps:
- Check if the Stack is Empty: If the stack is empty, return an error or None.
- Store the Top Node: Store the current top node in a temporary variable.
- Update the Top Reference: Update the top reference to point to the next node in the stack.
- Return the Stored Node's Value: Return the value of the stored top node.
After performing these steps, the stack will have the following structure:
Stack (Top -> Bottom):
Top -> 3 -> 2 -> 1
Pseudo Code
Function pop(stack):
# Check if the stack is empty
If stack.top is null:
Return None
# Store the current top node
temp = stack.top
# Update the top reference to the next node
stack.top = stack.top.next
# Return the value of the stored top node
Return temp.data
Python Program to Perform Stack Pop 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 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 popping:")
stack.traverse() # Output: 4 -> 3 -> 2 -> 1 -> None
popped_element = stack.pop()
print(f"Popped element: {popped_element}") # Output: 4
print("Stack after popping:")
stack.traverse() # Output: 3 -> 2 -> 1 -> None
This Python program defines a stack with methods for pushing elements onto the stack, popping elements from the stack, and traversing the stack. The pop method checks if the stack is empty, stores the current top node, updates the top reference, and returns the value of the stored top node.