Input: str = "algolesson"
Output: str = "nosselogla"
Input: str = "orange"
Output: str = "egnaro"
- Create one empty Stack.
- Push all the characters of the given string one by one into the stack.
- Create a new empty string.
- Add the top character of the stack to the empty string then pop the top character.
- Repeat the fourth step until the stack gets empty and you will get the reverse of the given string.
Example: C++ Code to reverse a string using stack.
//C++ Program to reverse String using Stack#include <iostream> #include <stack> using namespace std; int main() { string str = "orange"; stack<char> sc; string s = ""; //push all the char to the stack for (int i = 0; i < str.size(); i++) { sc.push(str[i]); } //pop all the char from the stack
// and add then to new empty string. while (!sc.empty()) { s += sc.top(); sc.pop(); } cout << "Reverser String " << s << endl; }
Reverser String egnaro
- Time Complexity: O(n)
- Space Complexity: O(n)
#include <bits/stdc++.h> using namespace std; int main() { string str = "orange"; //size of the given string int n = str.size(); for (int i = 0; i < n / 2; i++) { swap(str[i], str[n - 1 - i]); } cout << "Reverse String " << str << endl; }
Reverse String egnaro
.gif)





Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.