颠倒栈
题目:用递归颠倒一个栈,例如输入栈{1, 2, 3, 4, 5},1在栈顶。颠倒之后的栈为{5, 4, 3, 2, 1},5处在栈顶。
答:
#include "stdafx.h" #include <iostream> #include <stack> using namespace std; void AddStackBottom(stack<int> &s, int top) { if (s.empty()) { s.push(top); } else { int tmp = s.top(); s.pop(); AddStackBottom(s, top); s.push(tmp); } } void ReverseStack(stack<int> &s) { if (!s.empty()) { int top = s.top(); s.pop(); ReverseStack(s); AddStackBottom(s, top); } } int _tmain(int argc, _TCHAR* argv[]) { stack<int> s; s.push(5); s.push(4); s.push(3); s.push(2); s.push(1); ReverseStack(s); while (!s.empty()) { cout<<s.top()<<" "; s.pop(); }
cout<<endl; return 0; }
运行界面如下: