Stack Applications in C++: Determining Palindromes
In this article I’m going to demonstrate how to use the Stack class from the C++ Standard Template Library (STL) to determine if a string is a palindrome. Let’s get started.
Stack Class Review
The Stack is a data structure that stores data using a Last-in, First-out data flow. What this means is that the last data stored in the stack is the first data to come out of the stack. Stacks act like the trays you eat on at a cafeteria. If you want to get a tray, you take it off the top of the tray stack. If you need to put a tray back, you place it on the top of the tray stack. And that’s it, except for being able to examine the top item on the stack and checking to see if the stack is empty or not.
There are four Stack class member functions that implement these stack operations. These functions are: 1) push, to add data to a stack; 2) pop, to remove data from a stack; 3) top, to examine the data on the top of the stack; and 4) empty, which returns a true value if the stack is empty, or false otherwise.
Here is a quick program that demonstrates how to use the Stack member functions:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> numbers;
for (int i = 1; i <= 5; i++) {
numbers.push(i);
}
while…