Stack Applications in C++: Determining Palindromes

Mike McMillan
4 min readMar 27
Photo by Iva Rajović on Unsplash

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++) {
while (!numbers.empty()) {
cout << "The top of the stack is: "
<< << endl;

The integers 1 through 5 are placed on the stack and then taken off in the reverse order. Here is the output:

The top of the stack is: 5

The top of the stack is: 4

The top of the stack is: 3

The top of the stack is: 2

The top of the stack is: 1

Now that we’ve seen how a stack works, let’s use it to solve two problems.

Determining if a String is a Palindrome Using a Stack

A palindrome is a string that is spelled the same forward and backward. For example, “racecar” is a palindrome. Numbers can be palindromes as well, such as 2112.

Mike McMillan

Mike McMillan writes about computer programming and running. See more of his writing and courses at