【算法】用递归颠倒一个栈

题目:用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5}1在栈顶。颠倒之后的栈为{5, 4, 3, 2, 1}5处在栈顶。具体分析可以参考:

递归实现颠倒栈

下面给出源代码:

//递归实现颠倒栈
#include <iostream>
using namespace std;
#include <stack>

// Add an element to the bottom of a stack:

template<typename T> void AddToStackBottom(stack<T>& stack, T t)
{
	if(stack.empty())
	{
		stack.push(t);
	}
	else
	{
		T top = stack.top();
		stack.pop();
		AddToStackBottom(stack, t);
		stack.push(top);
	}
}

// Reverse a stack recursively in three steps:
// 1. Pop the top element
// 2. Reverse the remaining stack
// 3. Add the top element to the bottom of the remaining stack

template<typename T> void ReverseStack(stack<T>& stack)
{
	if(!stack.empty())
	{
		T top = stack.top();
		stack.pop();
		ReverseStack(stack);
		AddToStackBottom(stack, top);
	}
}

template<typename T> void PrintStack(stack<T>& myStack)
{
	T element;
	while(!myStack.empty())
	{
		element = myStack.top();
		cout<<element<<" ";
		myStack.pop();
	}
	cout<<endl;
}


int main()
{
	
	stack<int> myStack;

	myStack.push(1);myStack.push(2);myStack.push(3);myStack.push(4);myStack.push(5);myStack.push(6);
	PrintStack(myStack);

	myStack.push(1);myStack.push(2);myStack.push(3);myStack.push(4);myStack.push(5);myStack.push(6);
	//颠倒
	ReverseStack(myStack);
	PrintStack(myStack);
	return 0;
}

觉得很有意思,两次用到了递归,递归真的挺强大的。

你可能感兴趣的:(算法)