题目:用递归颠倒一个栈,例如输入栈{1, 2, 3, 4, 5},1在栈顶。颠倒之后的栈为{5, 4, 3, 2, 1},5处在栈顶。

答:

#include "stdafx.h"
#include <iostream>
#include <stack>

using namespace std;

void AddStackBottom(stack<int> &s, int top)
{
    if (s.empty())
    {
        s.push(top);
    }
    else
    {
        int tmp = s.top();
        s.pop();
        AddStackBottom(s, top);
        s.push(tmp);
    }
}

void ReverseStack(stack<int> &s)
{
    if (!s.empty())
    {
        int top = s.top();
        s.pop();
        ReverseStack(s);
        AddStackBottom(s, top);
    }
}


int _tmain(int argc, _TCHAR* argv[])
{
    stack<int> s;
    s.push(5);
    s.push(4);
    s.push(3);
    s.push(2);
    s.push(1);
    ReverseStack(s);
    while (!s.empty())
    {
        cout<<s.top()<<" ";
        s.pop();
    }
cout
<<endl; return 0; }

运行界面如下:

颠倒栈

相关文章:

  • 2022-12-23
  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
  • 2021-09-03
  • 2022-12-23
猜你喜欢
  • 2021-06-12
  • 2021-08-25
  • 2022-01-15
  • 2021-12-21
  • 2021-08-05
  • 2022-12-23
相关资源
相似解决方案