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