程序员面试题精选100题(39)-递归颠倒栈
来源:互联网 发布:阿里云可以搭建ss么 编辑:程序博客网 时间:2024/06/05 06:45
// 程序员面试题精选100题(39)-递归颠倒栈.cpp : 定义控制台应用程序的入口点。///*it is possible to reverse a stack in regular method resulting from the FIFO property of stack, so the method utilized two recursive function to meet that need.first divide the problem into two problems which can be settled by recursive function. then each recursive function realize a different function respectively */#include "stdafx.h"#include<iostream>#include <stack>using namespace std;void addelement(stack<int> &stk, int e)//add the element e to the bottom of the stk in a recursive method.{if (stk.empty()==0){int temp = stk.top();stk.pop();addelement(stk,e);stk.push(temp);}else{stk.push(e);}}void reversestk(stack<int> &stk)// notes: requiring a reference parameter to change the stk{if (stk.empty()==0){int temp = stk.top();stk.pop();reversestk(stk);//this is necessary and essentialaddelement(stk,temp);}else;}int _tmain(int argc, _TCHAR* argv[]){stack<int> stk;for (int i=1;i<=5;i++){stk.push(i);}//addelement(stk,8);reversestk(stk);while(stk.empty()==0){cout<<stk.top()<<" ";stk.pop();}system("pause");return 0;}