C++ an example of an algorithm that USES recursive functions and stack operations to reverse order a stack
- 2020-05-17 06:08:08
- OfStack
The example in this article describes the algorithm of C++ using recursive functions and stack operation to reverse order 1 stack. I will share it with you for your reference as follows:
Topic:
If a stack is pressed into 1, 2, 3, 4, 5, then the top and bottom of the stack are: 5, 4, 3, 2, 1.
Invert the stack to 1, 2, 3, 4, 5 at the top and bottom of the stack.
Use recursive functions instead of other data structures.
Problem solving ideas and code
1. Recursive function 1: return and remove the bottom element of the stack.
2, recursive function 2: reverse stack, call recursive function 1 implementation.
C + + implementation:
class Solution
{
public:
// Recursive function 1
static int getAndRemoveStackLastElem(stack<int>& s)
{
int result = s.top();
s.pop();
if (s.empty())
return result;
else
{
int last = getAndRemoveStackLastElem(s);
s.push(result);
return last;
}
}
// Recursive function 2
static void reverseStack(stack<int>& s)
{
if (s.empty())
return;
int i = getAndRemoveStackLastElem(s);
reverseStack(s);
s.push(i);
}
};
Program test case:
#include <iostream>
#include <stack>
using namespace std;
class Solution
{
public:
static int getAndRemoveStackLastElem(stack<int>& s)
{
int result = s.top();
s.pop();
if (s.empty())
return result;
else
{
int last = getAndRemoveStackLastElem(s);
s.push(result);
return last;
}
}
static void reverseStack(stack<int>& s)
{
if (s.empty())
return;
int i = getAndRemoveStackLastElem(s);
reverseStack(s);
s.push(i);
}
};
// Print a stack
void show(stack<int> s)
{
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
}
int main()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
cout << "Before reverse: " << endl;
show(s);
cout << "After reverse: " << endl;
Solution::reverseStack(s);
show(s);
system("pause");
}
Operation results:
Before reverse:
6 5 4 3 2 1
After reverse:
1 2 3 4 5 6
Please press any key to continue . . .
I hope this article is helpful to you C++ programming.