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

问题描述:

  一个栈依次压入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();
    }
}

 

posted on 2015-08-17 11:32  huashunli  阅读(304)  评论(0编辑  收藏  举报

导航