Search
 
SCRIPT & CODE EXAMPLE
 

CPP

reverse a stack in c++ using another stack

// C++ program to reverse a stack
// by using an extra stack
#include <bits/stdc++.h>
using namespace std;
 
// Function to transfer elements of
// the stack s1 to the stack s2
void transfer(stack<int>& s1,
              stack<int>& s2, int n)
{
    for (int i = 0; i < n; i++) {
 
        // Store the top element
        // in a temporary variable
        int temp = s1.top();
 
        // Pop out of the stack
        s1.pop();
 
        // Push it into s2
        s2.push(temp);
    }
}
 
// Function to reverse a stack using another stack
void reverse_stack_by_using_extra_stack(stack<int>& s,
                                        int n)
{
    stack<int> s2;
 
    for (int i = 0; i < n; i++) {
 
        // Store the top element
        // of the given stack
        int x = s.top();
 
        // Pop that element
        // out of the stack
        s.pop();
 
        transfer(s, s2, n - i - 1);
        s.push(x);
        transfer(s2, s, n - i - 1);
    }
}
 
// Driver Code
int main()
{
    int n = 5;
 
    stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
    s.push(5);
 
    reverse_stack_by_using_extra_stack(s, n);
 
    for (int i = 0; i < n; i++) {
        cout << s.top() << " ";
        s.pop();
    }
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: viewlist exaple win32 
Cpp :: sort vector in descending order c++ 
Cpp :: how to change the icon of an exe in c++ 
Cpp :: overload operator object function call 
Cpp :: codeforces problem 1700A solution in c++ 
Cpp :: array di struct 
Cpp :: zsh: segmentation fault ./provided_files.exe erosion X . 
Cpp :: c++ program to convert celsius to fahrenheit 
Cpp :: c++ put a function in a other thread 
Cpp :: vector literal in cpp 
Cpp :: C++ std::ofstream class members 
Cpp :: how to modify set C++ 
Cpp :: c++ hide credentials 
Cpp :: Corong_ExerciseNo3(1) 
Cpp :: c++ single comment 
Cpp :: for llop in c++ 
Cpp :: For auto map C 
Cpp :: crtdbg c++ 
Cpp :: The smallest element from three 
Cpp :: Boats to Save People leetcode solution in c++ 
Cpp :: c++ caps lock key 
Cpp :: leetcode 36 c++ 
Cpp :: Stream Overloading 
Cpp :: how the theam are store in database 
Cpp :: Jython Java Python 
Cpp :: racing horses codechef solution c++ 
Cpp :: get player pawn 
Cpp :: 1603. Design Parking System leetcode solution in c++ 
Cpp :: user inptu in cpp 
Cpp :: hello command not printing in c++ 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =