zoukankan      html  css  js  c++  java
  • 只用递归翻转栈

    先说句题外话,用递归实现栈的翻转纯粹就是用来练习的,递归做的效率显然不是最好的。面试喜欢问这个问题目的也就是考察对递归的理解。

    另外,不可能不用额外空间。递归就需要压栈,压栈就需要空间。

    做法:

    1. 取出栈顶
    2. 翻转栈
    3. 把第1步取出的元素放到栈底

    其中2,3两步就可以用递归做。

    参考程序(可编译):

    #include <iostream>
    #include <stack>
    using namespace std;
    
    class ReverseStack {
    public:
        void reverseStackRecursively(stack& stk) {
            if (stk.empty()) return;
            reverse_stk(stk);
        }
    private:
        void reverse_stk(stack& stk) {
            if (stk.empty()) return;
            int top_val = stk.top(); stk.pop();
            reverse_stk(stk);
            insert_to_bottom(stk, top_val);
        }
        
        void insert_to_bottom(stack& stk, int val) {
            if (stk.empty()) {
                stk.push(val);
                return;
            }
            int top_val = stk.top(); stk.pop();
            insert_to_bottom(stk, val);
            stk.push(top_val);
        }
    };
    
    int main()
    {
        stack stk;
        for (int i = 5; i >= 1; i--) {
            stk.push(i);
        }
        ReverseStack rs;
        rs.reverseStackRecursively(stk);
        while (!stk.empty()) {
            cout << stk.top() << " ";
            stk.pop();
        }
    }
    
  • 相关阅读:
    用了7年做到项目经理,女朋友却离开了我
    手把手教你建网站--程序小白适用篇
    燃尽图的学习与理解
    每周进度
    四人组队
    读构建之法之感
    两人组队,小学生的四则运算
    词汇统计
    AMQP中的架构和组成元素
    MSSQL机制
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/6901298.html
Copyright © 2011-2022 走看看