zoukankan      html  css  js  c++  java
  • 每天一道算法题(13)——使用递归颠倒栈

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


    思路

            1.弹出并保存栈顶元素
            2.递归,颠倒剩余的栈
            3.将栈顶元素保存至栈底



    代码
          
    //使用递归法,逆转栈
    template<typename T>
    bool reverseStack(stack<T> &s){
    	if(!s.empty())
    		return false;
    	T temp=s.top();
    	s.pop();
    	reverseStack(s);
    	adBottom(s,temp);
    	return true;
    }
    
    //某个元素,使用递归法,添加至栈底。
    template<typename T>
    void adBottom(stack<T> &s,T t){
    	if(!s.empty())
    		s.push(t);
    	else{
    		T temp=s.top();
    	        s.pop();
    		adBottom(s,t);
    		s.push(t);
    	}
    }











  • 相关阅读:
    βVAE学习
    条件GAN学习
    epoll的事件的状态
    RST报文产生的情况
    SIGPIPE信号产生原因
    methods事件
    for列表渲染
    if条件渲染
    data数据
    vue的简单上手
  • 原文地址:https://www.cnblogs.com/engineerLF/p/5393029.html
Copyright © 2011-2022 走看看