Stack (Data Structure)
A Stack is a linear data structure that follows the LIFO principle:
LIFO = Last In First Out
The element inserted last is removed first.
Example:
• Stack of plates
• Browser back button
• Undo operation in editors
Basic Operations on Stack
1. Push Operation
Adds an element to the top of the stack.
Example
Initial Stack:
[10, 20]
After push(30):
[10, 20, 30]
2. Pop Operation
Removes the top element from the stack.
Example
Initial Stack:
[10, 20, 30]
After pop():
[10, 20]
Removed element = 30
Stack Implementation Using List (Python)
In Python, a stack can be implemented easily using a list.
Program
# Stack implementation using list
stack = []
# Push operation
[Link](10)
[Link](20)
[Link](30)
print("Stack after push operations:")
print(stack)
# Pop operation
removed = [Link]()
print("Removed element:", removed)
print("Stack after pop operation:")
print(stack)
Output
Stack after push operations:
[10, 20, 30]
Removed element: 30
Stack after pop operation:
[10, 20]
Stack Methods in Python List
Operation Method
Push append()
Pop pop()
Peek/Top element stack[-1]
Check empty len(stack) == 0
Advantages of Stack
• Simple to implement
• Fast insertion and deletion
• Used in recursion, expression evaluation, undo operations
Stack Implementation Using Functions (Menu-Driven Program)
# Stack using List and Functions
stack = []
# Push Function
def push():
item = input("Enter element to push: ")
[Link](item)
print(item, "inserted into stack.")
# Pop Function
def pop():
if len(stack) == 0:
print("Stack Underflow! Stack is empty.")
else:
item = [Link]()
print("Deleted element:", item)
# Display Function
def display():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Stack elements are:")
for i in range(len(stack)-1, -1, -1):
print(stack[i])
# Peek Function
def peek():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Top element is:", stack[-1])
# Menu-Driven Program
while True:
print("\n----- STACK MENU -----")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
peek()
elif choice == 4:
display()
elif choice == 5:
print("Program terminated.")
break
else:
print("Invalid choice! Please try again.")
• Sample Output
• ----- STACK MENU -----
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter element to push: 50
50 inserted into stack.
Enter your choice: 1
Enter element to push: 100
100 inserted into stack.
Enter your choice: 4
Stack elements are:
100
50
Enter your choice: 2
Deleted element: 100
Enter your choice: 3
Top element is: 50
Enter your choice: 5
Program terminated.