Sunday 22 September 2024

Write a Program to reverse a string using stack

#include <iostream>

#include <stack>

#include <string>

using namespace std;


int main() {

    string input;

    stack<char> s;


    // Input the string to reverse

    cout << "Enter a string to reverse: ";

    cin>>input;

    // Push each character of the string onto the stack

    for (int i = 0; i < input.length(); i++) {

        s.push(input[i]); // Push the character at index i onto the stack

    }


    // Pop characters from the stack to get the reversed string

    string reversed;

    while (!s.empty()) {

        reversed += s.top();  // Get the top character from the stack

        s.pop();  // Remove the top character from the stack

    }


    // Display the reversed string

    cout << "Reversed string: " << reversed << endl;


    return 0;

}


Method 2


#include <iostream>

#include <stack> // Include the stack library

using namespace std;


// Function to reverse a string using a stack

string reverseString(const string& str) {

    stack<char> s; // Create a stack to hold characters


    // Push each character of the string onto the stack using a traditional for loop

    for (int i = 0; i < str.length(); i++) {

        s.push(str[i]); // Push the character at index i onto the stack

    }


    string reversedStr; // String to hold the reversed string


    // Pop characters from the stack to form the reversed string

    while (!s.empty()) {

        reversedStr += s.top(); // Get the top character from the stack

        s.pop(); // Remove the top character from the stack

    }


    return reversedStr; // Return the reversed string

}


int main() {

    string input;


    // Get user input

    cout << "Enter a string to reverse: ";

    getline(cin, input); // Read the entire line including spaces


    // Call the reverse function and print the result

    string reversed = reverseString(input);

    cout << "Reversed string: " << reversed << endl;


    return 0; 

}