Reverse a stack using recursion
问题描述
反转stack里面的元素,不能用while, for这样的循环机构,只允许用stack的一些操作,如:
empty(S)
push(S)
pop(S)
solution:
解决这个问题需要用到两个递归函数:
第一个递归函数从通配开始向下遍历stack中的每一个元素,直到stack为空
S1 –> | S2–> | S3–> | S4–> | S5–> |
---|---|---|---|---|
1 <– 2 3 4 5 | 1 2<– 3 4 5 | 1 2 3<– 4 5 | 1 2 3 4<– 5 | 1 2 3 4 5<– |
第二个递归函数从stack的最后一个元素开始向上依次将每个元素插入到stack的底部:
S10 | <–S9 | <–S8 | <–S7 | <–S6 |
---|---|---|---|---|
5 4 3 2 1 | 1 5 4 3 2 | 1 2 5 4 3 | 1 2 3 5 4 | 1 2 3 4 5 |
代码如下:
void insertBottom(Stack &stk, int val)
{
if(stk.empty())
{
stk.push(val);
return;
}else{
int temp = stk.top();
stk.pop();
insertBottom(stk, val);
stk.push(temp);
return;
}
}
void reverse(Stack &stk)
{
if(!stk.empty())
{
int temp = stk.top();
stk.pop();
reverse(stk);
insertBottom(stk, temp);
}
return;
}
完整代码:
#include <iostream>
using namespace std;
class Stack{
public:
Stack(int n){
num = n;
arr = new int[n]();
t = -1;
}
~Stack(){
delete [] arr;
}
bool empty()
{ return t<0; }
void push(int val)
{
t++;
if(t >= num)
{ cout<<"the stack is full"<<endl;
return;
}else
arr[t] = val;
return;
}
void pop()
{
if( t<0 )
{ cout<<"the stack is empty, can't pop'"<<endl;
return;
}else
t--;
}
int top()
{
if(t<0)
{ cout<<"the stack is empty";
return -1;
}else
return arr[t];
}
public:
int *arr;
private:
int num;
int t;
};
void print(Stack &stk)
{
if(!stk.empty())
{
int temp = stk.top();
cout<<temp;
stk.pop();
print(stk);
stk.push(temp);
}else{
cout<<endl;
}
return;
}
void insertBottom(Stack &stk, int val)
{
if(stk.empty())
{
stk.push(val);
return;
}else{
int temp = stk.top();
stk.pop();
insertBottom(stk, val);
stk.push(temp);
return;
}
}
void reverse(Stack &stk)
{
if(!stk.empty())
{
int temp = stk.top();
stk.pop();
reverse(stk);
insertBottom(stk, temp);
}
return;
}
int main()
{
int arr[] = {6,5,4,3,2,1};
Stack stk(10);
for(int i = 0; i<6; ++i)
stk.push(arr[i]);
print(stk);
reverse(stk);
print(stk);
}