Chinaunix首页 | 论坛 | 博客
  • 博客访问: 667016
  • 博文数量: 209
  • 博客积分: 26
  • 博客等级: 民兵
  • 技术积分: 326
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-21 09:29
文章分类

全部博文(209)

文章存档

2015年(6)

2014年(40)

2013年(154)

2012年(11)

我的朋友

分类: C/C++

2013-03-04 15:49:20

原文地址:尾递归及消除 作者:linux-person

尾递归:

点击(此处)折叠或打开

  1. /*Bad use of recursion:Printing a linked list*/
  2. /*No header*/
  3. void
  4. PrintList(List L)
  5. {
  6.     if (L != NULL) {
  7.         PrintElement(L->Element);
  8.         PrintList(L->Next);
  9.     }
  10. }
这个程序合法,表面无害,但如果链表L过大会越出栈空间,导致使程序崩溃。


用goto消除尾递归:


点击(此处)折叠或打开

  1. /*Bad use of recursion:Printing a linked list*/
  2. /*No header*/
  3. void
  4. PrintList(List L)
  5. {
  6. top:
  7.     if (L != NULL) {
  8.         PrintElement(L->Element);
  9.         L = L->next;
  10.         goto top;
  11.     }
  12. }

阅读(176) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~