A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/how-to-reverse-a-stack-in-cpp/ below:

How to Reverse a Stack in C++?

How to Reverse a Stack in C++?

Last Updated : 22 Mar, 2024

In C++, stacks are containers that store the elements in the last in-first out order(LIFO). In, this article, we will learn how we can reverse a stack in C++.

Example

Input:
stack<int> S ={5,4,3,2,1}
store
Output:
// Reversed Stack
stack<int> S ={1,2,3,4,5}

We can reverse a stack in C++ using anther set or any other sequential data container. We just have to reverse the order of the elements present in the stack. The below approach shows how to reverse stack using another stack.

Approach
  1. Declare a temporary stack named tempStack.
  2. Till the current stack is empty. Do the following:
    1. Push the top of currentStack to tempStack.
    2. Pop the top of the currentStack.
  3. The order of the elements will be reversed in the tempStack
  4. Assign the tempStack to currentStack.
C++ Program to Reverse a Stack

The following program illustrates how we can reverse a stack in C++:

C++
// C++ Program to illustrate how we can reverse a stack
#include <iostream>
#include <stack>
using namespace std;

// utility function to print stack
void printStack(stack<int> st)
{
    while (!st.empty()) {
        cout << st.top() << " ";
        st.pop();
    }
    cout << endl;
}

int main()
{
    // Initialize a stack
    stack<int> currentStack;

    // Push some elements into the stack
    currentStack.push(1);
    currentStack.push(2);
    currentStack.push(3);
    currentStack.push(4);
    currentStack.push(5);

    // Print the original stack
    cout << "Original stack: ";
    printStack(currentStack);

    // Reverse the stack
    stack<int> tempStack;
    while (!currentStack.empty()) {
        tempStack.push(currentStack.top());
        currentStack.pop();
    }
    currentStack = tempStack;

    // Print the reversed stack
    cout << "Reversed stack: ";
    printStack(currentStack);

    return 0;
}

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

Time Complexity: O(N) where N is the size of the stack.
Auxiliary Space: O(N)



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4