递归逆序打印单链表(c实现)

来源:互联网 发布:山西大学网络管理系统 编辑:程序博客网 时间:2024/05/18 01:45

递归逆序打印单链表。交换打印语句和递归调用的顺序,可以实现顺序打印和逆序打印链表。

#include <stdio.h>#include <stdlib.h>typedef struct Node {int data;struct Node *next;}Node ;Node *create_list(int *arr,const int len){if(arr==NULL||len<=0){return NULL;}Node *head = (Node*)malloc(sizeof(Node));head->data = arr[0];Node *p,*q = head;for(int i=1;i<len;i++){p = (Node*)malloc(sizeof(Node));p->data = arr[i];q->next = p;q = p;}q->next = NULL;return head;}void rprint(Node *head){if(head==NULL){return ;} else {rprint(head->next);printf("%d ",head->data);}}void print(Node *head){Node *p = head;while(p!=NULL){fprintf(stdout,"%d ",p->data);p = p->next;}}int main(void){int a[] = {1,2,3,4,5,6,7,8,9};const int len = sizeof(a)/sizeof(int);Node *head = create_list(a,len);print(head);printf("\n");rprint(head);return 0;}


0 0
原创粉丝点击