递归地反转一个栈

41 篇文章 1 订阅
//
// The code is used to reverse a stack recursively
//

#include <iostream>
#include <stack>
using namespace std;

// We can think about how we can reverse a stack with another stack.
// Cause stack is a structure first in last out, so at the first step 
// we should find a way to swap the top element to the bottom of the stack
void ReverseStackWithAnotherStack(stack<int> & destStack)
{
	if (destStack.size() == 0)return;
	for (int i = 0; i < destStack.size(); ++i)
	{
		// Get the top element of the stack.
		int top = destStack.top();
		destStack.pop();
		
		// Pump the remain elements to another stack
		int remain = destStack.size() - i;
		stack<int> tmpStack ;
		while (remain--)
		{
			tmpStack.push(destStack.top());
			destStack.pop();
		}
		// Push the top of the element into the bottom of the stack.
		destStack.push(top);
		
		// Pump the element from tmpStack to DestStack;
		while (!tmpStack.empty())
		{
			destStack.push(tmpStack.top());
			tmpStack.pop();
		}
	}
}

// As we know how to reverse a stack by another stack, we can use a recrsive function
// to take place the second stack.
void ReverseStackRecursively(stack<int> & destStack, int deep, const int & top)
{
	if (deep == 0)
	{
		destStack.push(top);
		return ;
	}
	int interimTop = destStack.top();
	destStack.pop();
	ReverseStackRecursively(destStack, deep - 1, top);
	destStack.push(interimTop);
}

void ReverseStackRecursively(stack<int> & destStack)
{
	if (destStack.size() == 0)return;
	for (int i = 0; i < destStack.size(); ++i)
	{
		int top = destStack.top();
		destStack.pop();
		int deep = destStack.size() - i;
		ReverseStackRecursively(destStack, deep, top);
	}
}

int main()
{
	stack<int> dest;
	for (int i = 0; i < 10; ++i)
	{
		dest.push(i);
	}
	
	ReverseStackWithAnotherStack(dest);
	while (!dest.empty())
	{
		cout<<dest.top()<<" ";
		dest.pop();
	}
	cout <<endl;
	
	for (int i = 0; i < 10; ++i)
	{
		dest.push(i);
	}
	ReverseStackRecursively(dest);
	while (!dest.empty())
	{
		cout<<dest.top()<<" ";
		dest.pop();
	}
	cout <<endl;
		
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值