How to Reverse a Word Using Stack in C++?
Last Updated :
12 Mar, 2024
In C++, we have a stack data structure that follows the Last In First Out (LIFO) principle. In this article, we will learn how to reverse a word using a stack in C++.
Example:
Input:
word = "GeeksforGeeks"
Output:
Reversed Word: skeeGrofskeeG
Reverse a String Using Stack in C++
To reverse a word using a stack in C++, we can push each character of the word onto the stack and then pop them off. Since a stack is a LIFO data structure, the characters will be popped off in the reverse order they were pushed on, effectively reversing the word.
Approach
- First, create an empty stack.
- Now, push all characters of the word to the stack.
- Start popping the characters from the stack and store them back in the reversed_word.
- Finally, we get the reversed word in reversed_word.
C++ Program to Reverse a String Using Stack
The below example demonstrates how we can reverse a word using a stack in C++.
C++
// C++ Program to illustrate how to reverse a word using a
// stack
#include <iostream>
#include <stack>
using namespace std;
int main()
{
// Declaring and initializing the original word
string word = "GeeksforGeeks";
cout << "Original Word: " << word << endl;
// Creating a stack to store characters
stack<char> s;
// Push each character of the word onto the stack
for (char c : word) {
s.push(c);
}
// Declaring a string to store the reversed word
string reversed_word = "";
// Pop each character from the stack and append it to
// the reversed word
while (!s.empty()) {
reversed_word += s.top();
s.pop();
}
// Print the reversed word
cout << "Reversed Word: " << reversed_word << endl;
return 0;
}
OutputOriginal Word: GeeksforGeeks
Reversed Word: skeeGrofskeeG
Time Complexity: O(N), where N is the length of word.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...