Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Implement a Stack using Linked List
When implementing a stack data structure using a linked list, we need methods to add (push) elements to the top and remove (pop) elements from the top. In a stack, the last element added is the first one to be removed (LIFO - Last In First Out).
Node Class
First, we create a Node class to represent individual elements in the linked list ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
Stack Implementation
The Stack class uses a linked list where the head pointer represents the top of the stack ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
print(f"Pushed {data} to stack")
def pop(self):
if self.head is None:
print("Stack is empty")
return None
else:
popped_value = self.head.data
self.head = self.head.next
return popped_value
def display(self):
if self.head is None:
print("Stack is empty")
else:
current = self.head
elements = []
while current:
elements.append(str(current.data))
current = current.next
print("Stack (top to bottom):", " -> ".join(elements))
# Example usage
stack = Stack()
# Push elements
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
# Pop elements
print(f"Popped: {stack.pop()}")
print(f"Popped: {stack.pop()}")
stack.display()
print(f"Popped: {stack.pop()}")
stack.pop() # Try to pop from empty stack
Pushed 10 to stack Pushed 20 to stack Pushed 30 to stack Stack (top to bottom): 30 -> 20 -> 10 Popped: 30 Popped: 20 Stack (top to bottom): 10 Popped: 10 Stack is empty
Interactive Stack Operations
Here's an interactive version that allows user input for stack operations ?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
return None
else:
popped_value = self.head.data
self.head = self.head.next
return popped_value
def is_empty(self):
return self.head is None
# Interactive stack operations
stack = Stack()
while True:
print("\nStack Operations:")
print("1. push <value>")
print("2. pop")
print("3. quit")
user_input = input("What operation would you like to perform? ").split()
if not user_input:
continue
operation = user_input[0].lower()
if operation == "push" and len(user_input) > 1:
try:
value = int(user_input[1])
stack.push(value)
print(f"Pushed {value} to stack")
except ValueError:
print("Please enter a valid number")
elif operation == "pop":
result = stack.pop()
if result is None:
print("Stack is empty")
else:
print(f"Popped value: {result}")
elif operation == "quit":
print("Exiting...")
break
else:
print("Invalid operation. Use: push <value>, pop, or quit")
Key Operations
| Operation | Time Complexity | Description |
|---|---|---|
push() |
O(1) | Add element to top of stack |
pop() |
O(1) | Remove and return top element |
is_empty() |
O(1) | Check if stack is empty |
How It Works
The stack implementation works as follows:
- Push Operation: Creates a new node, sets its next pointer to the current head, and updates head to point to the new node
- Pop Operation: Removes the head node, updates head to point to the next node, and returns the removed data
- LIFO Principle: The head always points to the most recently added element (top of stack)
Conclusion
A stack using linked list provides dynamic memory allocation and constant time complexity for push and pop operations. The head pointer always represents the top of the stack, maintaining the LIFO principle efficiently.
