//
// 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;
}
递归地反转一个栈
最新推荐文章于 2024-07-10 16:08:48 发布