每天一道算法题(13)——使用递归颠倒栈

来源:互联网 发布:淘宝模特招聘兼职 编辑:程序博客网 时间:2024/06/06 02:48

       题目:用递归颠倒一个栈。例如输入栈{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);}}











0 0
原创粉丝点击