Chinaunix首页 | 论坛 | 博客
  • 博客访问: 457302
  • 博文数量: 56
  • 博客积分: 517
  • 博客等级: 下士
  • 技术积分: 751
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-12 18:16
文章分类

全部博文(56)

文章存档

2015年(2)

2014年(6)

2013年(29)

2012年(17)

2011年(2)

分类: C/C++

2013-03-03 12:56:37

尾递归:

点击(此处)折叠或打开

  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. }

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

shakingWaves2013-12-30 21:33:38

还是用while循环吧,goto语句还是用得很少。。