C++ - Stacks Part 3: Practical Applications of Stacks
Stacks are used in algorithms that require LIFO operations, such as parsing, recursion simulation, and backtracking.
Examples and Explanation
Reversing a String
std::stack<char> charStack;
std::string str = "hello";
for (char c : str) {
charStack.push(c);
}
while (!charStack.empty()) {
std::cout << charStack.top();
charStack.pop();
}
// Output: olleh
Explanation: Characters are pushed into the stack in order and then popped out in reverse order.
Checking Balanced Parentheses
bool isBalanced(const std::string &expression) {
std::stack<char> stack;
for (char c : expression) {
if (c == '(') stack.push(c);
else if (c == ')') {
if (stack.empty()) return false;
stack.pop();
}
}
return stack.empty();
}
Explanation: Stacks help in keeping track of unmatched parentheses, a common task in parsing expressions.
Implementing Undo Functionality
std::stack<std::string> undoStack;
undoStack.push("Action1");
undoStack.push("Action2");
std::cout << "Undo: " << undoStack.top(); // Output: Action2
undoStack.pop();
Explanation: Stacks provide an easy way to implement undo/redo functionality by managing the sequence of actions.