Using recursive functions and a reverse stack Stack (C ++)

Title: 1,2,3,4,5 pressed into a stack sequentially, then the top of the stack to the bottom of the stack is 5,4,3,2,1, respectively. After this transposed stack from the stack to the bottom of the stack 1,2,3,4,5, i.e. in reverse order to achieve the stack of elements, but can only use a recursive function to implement, can not use other data structures. (Not to say that the code can not appear in the stack )

Enter a description:

The first line of the input data as an integer number N of elements in the stack.
The next line N represents integers to sequentially stack each element from the bottom of the stack.

Output Description:

Each row represents the output element of the elements in the stack in reverse order

Using recursive functions and a reverse stack Stack (C ++)

Topic Note:
1. Using a recursive function and stack to achieve, do not forget the stack

#include <iostream>
#include <stack>
using namespace std;

void reverse(stack<int>& s)
{
    if(s.empty())
    {
        return;
    }
    int m=s.top();
    s.pop();
    reverse(s);
    s.push(m);//每一次的递归深入,m变量是不一样的
}

int main()
{
    int n;
    while(cin>>n)
    {
        stack<int> s;
        int a=0;
        for(int i=0;i<n;++i)
        {
            cin>>a;
            s.push(a);
        }
        reverse(s);
        for(int i=0;i<n;++i)
        {
            cout<<s.top()<<" ";
            s.pop();
        }
    }
    return 0;
}

Guess you like

Origin blog.51cto.com/14233078/2471371