Practical 4-Stack Stack Datastructure
Practical 4-Stack Stack Datastructure
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle,
meaning the last element added to the stack is the first one to be removed. Think of it as a
stack of plates: you can only take the top plate off the stack, and when you add a plate, you
place it on top.
Key Operations:
1. Push: Add an element to the top of the stack.
2. Pop: Remove the top element from the stack.
3. Peek/Top: View the top element without removing it.
4. isEmpty: Check if the stack is empty.
5. isFull (optional, for fixed-size stacks): Check if the stack is full.
1
# Check if stack is empty
def is_empty(self):
return len(self.stack) == 0
# Example usage
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(s.peek()) # Output: 3
print(s.pop()) # Output: 3
print(s.pop()) # Output: 2
print(s.is_empty()) # Output: False
print(s.pop()) # Output: 1
print(s.is_empty()) # Output: True
2
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
pop method: This method removes and returns the top item from the stack.
if not self.is_empty(): Checks if the stack is not empty before attempting to pop. This
prevents errors from popping from an empty stack.
return self.stack.pop(): If the stack has elements, it uses the pop method of the list to
remove and return the last item.
else: return "Stack is empty": If the stack is empty, it returns a message indicating
that.
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty"
peek method: This method returns the top item of the stack without removing it.
if not self.is_empty(): Checks if the stack is not empty.
return self.stack[-1]: Returns the last item in the list (the top of the stack).
else: return "Stack is empty": Returns a message if the stack is empty.
def is_empty(self):
return len(self.stack) == 0
is_empty method: This method checks if the stack is empty.
return len(self.stack) == 0: Returns True if the length of the stack is zero, indicating
it's empty; otherwise, it returns False.
Example Usage:
s = Stack()
Creates an instance of the Stack class.
s.push(1)
s.push(2)
s.push(3)
Pushes three items (1, 2, 3) onto the stack.
3
print(s.peek()) # Output: 3
Prints the top item of the stack without removing it. Expected output is 3.
print(s.pop()) # Output: 3
Removes and prints the top item of the stack. Expected output is 3.
print(s.pop()) # Output: 2
Removes and prints the next top item. Expected output is 2.
4
else:
return "Stack is empty"
# Check if the stack is empty (helper method for pop)
def is_empty(self):
return len(self.stack) == 0
# Example usage
s = Stack()
s.push(10)
s.push(20)
s.push(30)
print(s.pop()) # Output: 30
print(s.pop()) # Output: 20
print(s.pop()) # Output: 10
print(s.pop()) # Output: Stack is empty
Key Points:
push(item): Adds an item to the top of the stack.
pop (): Removes and returns the top item from the stack. If the stack is empty, it
handles the underflow case by checking with is_empty().
5
# Pop operation
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
# Example usage
s = Stack()
6
s.pop() # 4th pop
s.pop() # 5th pop
s.pop() # 6th pop
Here's how you can push 10 words onto a stack, pop 6 of them,
and print the remaining words in the stack using for loop:
class Stack:
def __init__(self):
self.stack = []
# Push operation
def push(self, item):
self.stack.append(item)
# Pop operation
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
7
def is_empty(self):
return len(self.stack) == 0
# Example usage
s = Stack()
# Push 10 words onto the stack
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew",
"kiwi", "lemon"]
for word in words:
s.push(word)
8
# Push operation
def push(self, item):
if not self.is_full():
self.stack.append(item)
print(f"Pushed: {item}")
else:
print("Stack is full. Cannot push.")
# Pop operation
def pop(self):
if not self.is_empty():
popped_item = self.stack.pop()
print(f"Popped: {popped_item}")
return popped_item
else:
print("Stack is empty. Cannot pop.")
# Peek operation
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty. No top element.")
9
return len(self.stack) == self.size
# Example usage
s = Stack()
# Capture 10 numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Perform operations
print("Top element:", s.peek()) # View the top element
# Pop 5 elements
for _ in range(5):
s.pop()
# Check if the stack is empty or full
print("Is the stack empty?", s.is_empty())
print("Is the stack full?", s.is_full())
# View remaining elements
print("Remaining elements in the stack:", s.stack)
Explanation of Key Operations:
1. Push: The push method adds an item to the stack if it’s not full.
2. Pop: The pop method removes the top item from the stack if it’s not empty.
3. Peek: The peek method returns the top item without removing it.
4. isEmpty: The is_empty method checks if the stack has no elements.
5. isFull: The is_full method checks if the stack has reached its maximum size.
Example Output:
10
When you run this code, the output will reflect the operations performed, such as which
numbers are pushed and popped, and the status of the stack.
Applications of Stacks:
Backtracking algorithms (e.g., maze-solving)
Undo/Redo functionality in text editors
Expression evaluation (e.g., infix to postfix conversion)
Call stack in programming languages
11