C++ Stacks
A stack is a container that follows the Last In, First Out (LIFO) principle. In C++, stacks are part of the Standard Template Library (STL) and can be implemented using the stack
class. Stacks are useful for managing data in scenarios where you need to access the most recently added element first.
Key Topics
- Overview of Stacks
- Declaring Stacks
- Common Stack Operations
- Iterating Over Stacks
- Exercises with Stacks
Overview of Stacks
Stacks provide several advantages:
- Efficient access to the last added element.
- Simple interface for adding and removing elements.
- Commonly used in algorithms like depth-first search and expression evaluation.
Declaring Stacks
To declare a stack, include the stack
header and use the following syntax:
#include
stack myStack;
Common Stack Operations
Here are some common operations you can perform on stacks:
push()
: Adds an element to the top of the stack.pop()
: Removes the top element from the stack.top()
: Returns the top element of the stack without removing it.empty()
: Checks if the stack is empty.size()
: Returns the number of elements in the stack.
Example: Basic Stack Operations
#include
#include
using namespace std;
int main() {
stack myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
cout << "Top element: " << myStack.top() << endl;
myStack.pop();
cout << "Top element after pop: " << myStack.top() << endl;
cout << "Stack size: " << myStack.size() << endl;
return 0;
}
Output:
Iterating Over Stacks
Stacks do not provide direct iteration methods like vectors or lists. However, you can access elements by popping them off the stack, but this changes the stack's state. Therefore, it's common to use a temporary stack to preserve the original stack.
Example: Iterating Using a Temporary Stack
#include
#include
using namespace std;
int main() {
stack myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
stack tempStack;
cout << "Stack elements: ";
while (!myStack.empty()) {
cout << myStack.top() << " ";
tempStack.push(myStack.top());
myStack.pop();
}
// Restore the original stack
while (!tempStack.empty()) {
myStack.push(tempStack.top());
tempStack.pop();
}
return 0;
}
Output:
Exercises with Stacks
Here are some exercises to practice your understanding of stacks:
- Implement a program that reverses a string using a stack.
- Write a function that checks for balanced parentheses in an expression using a stack.
- Simulate a simple undo operation using a stack to keep track of previous actions.
Key Takeaways
- Stacks are LIFO data structures that allow efficient access to the last added element.
- Common operations include pushing, popping, and accessing the top element.
- Stacks are useful in various algorithms and applications, such as expression evaluation and backtracking.
- Iterating over stacks requires careful handling to preserve the original stack state.