用递归函数和栈操作逆序一个栈

↘锁芯ラ 提交于 2020-01-22 01:06:25

问题描述:

  一个栈依次压入1,2,3,4,5那么从栈顶到栈底分别为5,4,3,2,1。将这个栈转置后,从栈顶到栈底为1,2,3,4,5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,而不能用另外的数据结构。

 

实现代码:

#include <stack>
#include <stdio.h>
using namespace std;

int GetAndRemoveBottom(stack<int> &ss)
{
    int top, bottom;
    top = ss.top();
    ss.pop();
    if(ss.empty())
        return top;
    bottom = GetAndRemoveBottom(ss);
    ss.push(top);
    return bottom;
}

void ReverseStack(stack<int> &ss)
{
    if(ss.empty()) return ;
    int bottom = GetAndRemoveBottom(ss);
    ReverseStack(ss);
    ss.push(bottom);
}

int main()
{
    stack<int> ss;
    for(int i = 1; i <= 5; i++)
        ss.push(i);
    ReverseStack(ss);
    while(!ss.empty())
    {
        printf("%d ", ss.top());
        ss.pop();
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!