In this section, we will provide practical exercises to reinforce your understanding of stacks. Each exercise will include a problem statement, followed by a solution and an explanation. These exercises will help you apply the concepts and operations related to stacks in real-world scenarios.
Exercise 1: Implement a Stack using an Array
Problem Statement: Implement a stack using an array. Your stack should support the following operations:
push(x): Push elementxonto the stack.pop(): Remove the element on top of the stack and return it.peek(): Get the top element.isEmpty(): Return whether the stack is empty.
Solution:
class Stack:
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
if not self.isEmpty():
return self.stack.pop()
else:
return "Stack is empty"
def peek(self):
if not self.isEmpty():
return self.stack[-1]
else:
return "Stack is empty"
def isEmpty(self):
return len(self.stack) == 0
# Example usage:
s = Stack()
s.push(1)
s.push(2)
print(s.peek()) # Output: 2
print(s.pop()) # Output: 2
print(s.isEmpty()) # Output: False
print(s.pop()) # Output: 1
print(s.isEmpty()) # Output: TrueExplanation:
- The
Stackclass uses a list (self.stack) to store elements. - The
pushmethod appends an element to the end of the list. - The
popmethod removes and returns the last element of the list if the stack is not empty. - The
peekmethod returns the last element without removing it if the stack is not empty. - The
isEmptymethod checks if the list is empty.
Exercise 2: Reverse a String using a Stack
Problem Statement: Write a function that takes a string as input and uses a stack to reverse the string.
Solution:
def reverseString(s):
stack = []
for char in s:
stack.append(char)
reversed_string = ''
while stack:
reversed_string += stack.pop()
return reversed_string
# Example usage:
input_string = "hello"
print(reverseString(input_string)) # Output: "olleh"Explanation:
- The function
reverseStringinitializes an empty stack. - It iterates over each character in the input string and pushes it onto the stack.
- It then pops each character from the stack and appends it to the
reversed_string. - The stack's LIFO (Last In, First Out) property ensures the string is reversed.
Exercise 3: Check for Balanced Parentheses
Problem Statement: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Solution:
def isValid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
# Example usage:
print(isValid("()")) # Output: True
print(isValid("()[]{}")) # Output: True
print(isValid("(]")) # Output: False
print(isValid("([)]")) # Output: False
print(isValid("{[]}")) # Output: TrueExplanation:
- The function
isValiduses a stack to keep track of opening brackets. - It iterates over each character in the input string.
- If the character is a closing bracket, it checks if the top element of the stack matches the corresponding opening bracket.
- If the character is an opening bracket, it pushes it onto the stack.
- Finally, it returns
Trueif the stack is empty (all brackets are matched), otherwiseFalse.
Common Mistakes and Tips
- Not Checking for Empty Stack: When popping from the stack, always check if the stack is empty to avoid errors.
- Incorrect Mapping: Ensure the mapping of closing to opening brackets is correct when checking for balanced parentheses.
- Edge Cases: Consider edge cases such as an empty string or a string with only one type of bracket.
Conclusion
In this section, we covered practical exercises to help you understand and implement stacks. We implemented a stack using an array, reversed a string using a stack, and checked for balanced parentheses. These exercises should give you a solid foundation in working with stacks and understanding their applications.
Data Structures Course
Module 1: Introduction to Data Structures
Module 2: Lists
Module 3: Stacks
- Introduction to Stacks
- Basic Operations with Stacks
- Stack Implementation
- Applications of Stacks
- Exercises with Stacks
Module 4: Queues
- Introduction to Queues
- Basic Operations with Queues
- Circular Queues
- Priority Queues
- Exercises with Queues
Module 5: Trees
Module 6: Graphs
- Introduction to Graphs
- Graph Representation
- Graph Search Algorithms
- Shortest Path Algorithms
- Applications of Graphs
- Exercises with Graphs
