码迷,mamicode.com
首页 > 其他好文 > 详细

用递归函数和栈操作逆序一个栈

时间:2020-07-26 01:27:13      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:amp   push   递归   end   ret   mic   返回   不同的   empty   

代码:

#include <iostream>
#include <stack>
using namespace std;
int g_a_r_l_e(stack<int>&stackdata)//取栈顶元素并在栈中将其删除;
                                                         //注意这里转引用,如果不传引用每次递归会传入不同的stack,这样会出现错误                                                       
{
  int top_val = stackdata.top();
  stackdata.pop();
  if(stackdata.empty()){
    return top_val;
  }
  else{
    int last = g_a_r_l_e(stackdata);
    stackdata.push(top_val);
    return last;
  }
}
void reverse(stack<int>&stackdata)//每次递归都是取执行完g_a_r_l_e()的返回值,
                                //直到stackdata.empty=1,这时把g_a_r_l_e()的返回值入栈
{
  if(stackdata.empty()){
    return ;
  }
  else{
    int i = g_a_r_l_e(stackdata);
    reverse(stackdata);
    stackdata.push(i);
  }
}

int main()
{
  stack<int>stackdata1;
  int a[]={1,2,3,4,5,6};
  for(int i=0;i<6;i++)
  {
    stackdata1.push(a[i]);
  }
  reverse(stackdata1);
  cout<<"逆序后栈数据:"<<endl;
  //遍历逆序后的栈
  while(!stackdata1.empty()){
    int tp = stackdata1.top();
    std::cout << tp << ‘\n‘;
    stackdata1.pop();
  }
}
 
结果:
 
技术图片

 

 

 

 

 
 
 
 

用递归函数和栈操作逆序一个栈

标签:amp   push   递归   end   ret   mic   返回   不同的   empty   

原文地址:https://www.cnblogs.com/shiheyuanfang/p/13378002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!