【演算法】用遞迴顛倒一個棧

pengfoo發表於2012-10-04

題目:用遞迴顛倒一個棧。例如輸入棧{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;
}

覺得很有意思,兩次用到了遞迴,遞迴真的挺強大的。

相關文章