C language to reverse the stack method

  • 2020-04-02 02:44:40
  • OfStack

The example of this article describes the C language implementation of the stack inversion method, very practical skills. Share with you for your reference.

The specific implementation method is as follows:


#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>

using namespace std;

void initializeStack(stack<int> &st)
{
 for(int i = 1; i <= 5; i++)
 st.push(i);
}

void addToStack(stack<int>& st, int i)
{
 if(st.empty())
 st.push(i);
 else {
 int top = st.top();
 st.pop();
 addToStack(st, i);
 st.push(top);
 }
}

void reverseStack(stack<int> &st)
{
 if(st.empty())
 return;

 int top = st.top();
 st.pop();
 reverseStack(st);
 addToStack(st, top);
}

void print(stack<int> st)
{
 if(st.empty())
 return;
 else {
 int top = st.top();
 st.pop();
 print(st);
 cout << top << " ";
 }
}

void main()
{
 stack<int> st;
 initializeStack(st);
 print(st);
 cout << endl;
 reverseStack(st);
 print(st);
}

I hope that this paper is helpful to the learning of C programming algorithm design.


Related articles: