reverse a stack in c++ using another stack

To reverse a stack in C++ using another stack, you can follow these steps:

  1. Create two stacks: the original stack and a temporary stack.
  2. While the original stack is not empty, do the following:
  3. Pop an element from the original stack and store it in a variable.
  4. Push the element into the temporary stack.
  5. Once the original stack is empty, the temporary stack will contain the elements in reverse order.
  6. Move the elements from the temporary stack back to the original stack.
  7. While the temporary stack is not empty, do the following:
    • Pop an element from the temporary stack and store it in a variable.
    • Push the element back into the original stack.

Here is an example implementation in C++:

#include <iostream>
#include <stack>

void reverseStack(std::stack<int>& originalStack) {
    std::stack<int> tempStack;

    while (!originalStack.empty()) {
        int element = originalStack.top();
        originalStack.pop();
        tempStack.push(element);
    }

    while (!tempStack.empty()) {
        int element = tempStack.top();
        tempStack.pop();
        originalStack.push(element);
    }
}

int main() {
    std::stack<int> myStack;
    myStack.push(1);
    myStack.push(2);
    myStack.push(3);
    myStack.push(4);
    myStack.push(5);

    std::cout << "Original stack: ";
    while (!myStack.empty()) {
        std::cout << myStack.top() << " ";
        myStack.pop();
    }

    reverseStack(myStack);

    std::cout << "\nReversed stack: ";
    while (!myStack.empty()) {
        std::cout << myStack.top() << " ";
        myStack.pop();
    }

    return 0;
}

This implementation creates a stack myStack with elements 1, 2, 3, 4, and 5. It then calls the reverseStack function to reverse the stack. After the reversal, the elements are printed in reverse order, resulting in the output:

Original stack: 5 4 3 2 1
Reversed stack: 1 2 3 4 5

I hope this helps! Let me know if you have any further questions.