尾递归及消除

230阅读 0评论2013-03-04 ywh147
分类:C/C++

尾递归:

点击(此处)折叠或打开

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

上一篇:codeblocks自动完成
下一篇:服务器响应HTTP请求状态码简单注释