【编程题目】颠倒栈☆

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

思路:我自己没做出来,因为总觉得用不上递归。看了网上答案http://blog.csdn.net/cxllyg/article/details/7655935 根据里面的思路 自己照着写了一遍

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

//自己没有理解用递归的含义 看了网上的答案http://blog.csdn.net/cxllyg/article/details/7655935

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

void pushToStackBottom(vector<int> & stack, int t)
{
    if (stack.empty())
    {
        stack.push_back(t);
    }
    else
    {
        int T = stack.back();
        stack.pop_back();
        pushToStackBottom(stack, t);
        stack.push_back(T);
    }
}

void reverseStack(vector<int> &stack)
{
    if (!stack.empty())
    {
        int t = stack.back();
        stack.pop_back();
        reverseStack(stack);
        pushToStackBottom(stack, t);
    }
}

int main()
{
    vector<int> s;
    s.push_back(1);
    s.push_back(2);
    s.push_back(3);
    s.push_back(4);
    s.push_back(5);

    reverseStack(s);
    return 0;
}
原文地址:https://www.cnblogs.com/dplearning/p/3916861.html