zoukankan      html  css  js  c++  java
  • 颠倒栈 【微软面试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);
    }
  • 相关阅读:
    vb.net的数据类型
    PHP常用函数
    399. Evaluate Division
    329. Longest Increasing Path in a Matrix
    415. Add Strings
    463 Island Perimeter
    400. Nth Digit
    401. Binary Watch
    391. Perfect Rectangle
    406. Queue Reconstruction by Height
  • 原文地址:https://www.cnblogs.com/tractorman/p/4104966.html
Copyright © 2011-2022 走看看