• 颠倒栈 【微软面试100题 第六十六题】


    题目要求:

      用递归颠倒一个栈。

      例如输入栈{1,2,3,4,5},1在栈顶。颠倒之后的栈为{5,4,3,2,1},5处在栈顶。

    题目分析:

      令函数申明为:void ReverseStack(stack oldStack);

    代码实现:

    #include <iostream>
    #include <stack>
    
    using namespace std;
    
    void ReverseStack(stack<int> &oldStack);
    void PrintStack(stack<int> s);
    
    int main(void)
    {
        stack<int> oldStack;
        oldStack.push(5);
        oldStack.push(4);
        oldStack.push(3);
        oldStack.push(2);
        oldStack.push(1);
        cout << "原栈为:";
        PrintStack(oldStack);
        cout << endl;
        ReverseStack(oldStack);
        cout << "颠倒后的栈为:";
        PrintStack(oldStack);
        cout << endl;
        return 0;
    }
    void PrintStack(stack<int> s)
    {
        if(s.empty())
            return;
        int tmp = s.top();
        cout << tmp << " ";
        s.pop();
        PrintStack(s);
        s.push(tmp);
    }
    void PutToBottom(stack<int> &newStack,int tmp)
    {
        if(newStack.empty())
        {
            newStack.push(tmp);
            return;
        }
        int newTmp = newStack.top();
        newStack.pop();
        PutToBottom(newStack,tmp);
        newStack.push(newTmp);
    }
    void ReverseStack(stack<int> &oldStack)
    {
        if(oldStack.empty())
            return;
        int tmp = oldStack.top();
        oldStack.pop();
        ReverseStack(oldStack);
        PutToBottom(oldStack,tmp);
    }
  • 相关阅读:
    APIJSON
    pinyin4j 中文转拼音
    JsonPath
    rocket-api
    SpringCloudAlibaba和SpringCloud的区别
    jar分离lib打包
    java8 forEach
    java8 CompletableFuture
    IE浏览器根证书问题
    基于Win服务的标签打印(模板套打)[转]
  • 原文地址:https://www.cnblogs.com/tractorman/p/4104966.html
Copyright © 2020-2023  润新知