单链表逆置递归算法(C语言)

#include <stdio.h> typedef int Element; typedef struct LinkListType { Element data; struct LinkListType * next; } LinkList ; //reverse a link list recursively LinkList * reverse(LinkList * pre, LinkList * cur) { if(!cur) return pre; LinkList * head = reverse(cur, cur->next); cur->next = pre; return head; } int main() { int i; LinkList *head = NULL, * pre=NULL, * cur=NULL; //initial a link list for(i=0; i<12; i++) { cur = (LinkList*)malloc(sizeof(LinkList)); if(!head) head = cur; cur->data = i; cur->next = NULL; if(pre) pre->next = cur; pre = cur; } cur = head; //print the original list to stdout while(cur) { printf(“%d -> “, cur->data); cur = cur->next; } printf(“#/n”); //reverse the link list head = reverse(NULL, head); //print the reversed link list to stdout while(head) { printf(“%d -> “, head->data); head = head->next; } printf(“#/n”); }

    原文作者:递归算法
    原文地址: https://blog.csdn.net/huoyin/article/details/6064204
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞