反转一个链表。递归算法

反转一个链表。递归算法

分类: 数据结构与算法   297人阅读  评论(0)  收藏  举报
[cpp]  view plain copy
  1. // ReverseList.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5.   
  6. struct node{  
  7.     int m_num;  
  8.     struct node* pnext;  
  9.     node(int num)  
  10.     {  
  11.         m_num=num;  
  12.         pnext=NULL;  
  13.     }  
  14. };  
  15.   
  16. node* reverse(node*  head)  
  17. {  
  18.     static node*  new_head;  
  19.     if(head==NULL)  
  20.         return NULL;  
  21.   
  22.     if(head->pnext !=NULL)  
  23.     {  
  24.         reverse(head->pnext);  
  25.         head->pnext->pnext=head;  
  26.         head->pnext=NULL;  
  27.     }  
  28.     else  
  29.         new_head=head;  
  30.       
  31.     return new_head;  
  32. }  
  33.   
  34. void travel(node*  head)  
  35. {  
  36.     node* pwalker=head;  
  37.     while(pwalker!=NULL)  
  38.     {  
  39.         printf("%3d",pwalker->m_num);  
  40.         pwalker=pwalker->pnext;  
  41.     }  
  42.     printf("\n");  
  43.   
  44. }  
  45. int main(int argc, char* argv[])  
  46. {  
  47.     node* head1=new node(1);  
  48.     node* node2=new node(2);  
  49.     node* node3=new node(3);  
  50.     head1->pnext=node2;  
  51.     node2->pnext=node3;  
  52.     travel(head1);  
  53.     node* rev=reverse(head1);  
  54.     travel(rev);  
  55.     printf("Hello World!\n");  
  56.     return 0;  
  57. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值