单链表----递归建立,递归反转,递归打印

/*
*    auther: Try86
*    time:2012/9/25 13:14
*    dec:单链表:递归建立,递归反转,递归打印
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct list                 //单链表节点结构
{
   int data;
   struct list *p_next;
}List;

int main(void)
{
   int num = 0;                    //统计单链表的节点数
   List *head = NULL;              //链表头指针
   List *p_cur = NULL;
   void build_list(List **head, List *p_cur, int *pnum);   
void list_reverse(List **head, List *p_cur, List *p_nt, int *pnum); void print(List *ptr); build_list(&head, p_cur, &num); assert(NULL != head); //判断是否为空表 list_reverse(&head, head, head->p_next, &num); print(head); return 0; } //递归建立单链表 void build_list(List **head, List *p_cur, int *pnum) { int num; List *ptr = NULL; if (scanf("%d", &num) && num > 0) { ++(*pnum); if ((ptr = (List *)malloc(sizeof(List))) != NULL) { ptr->data = num; ptr->p_next = NULL; if (NULL == *head) { *head = ptr; p_cur = ptr; p_cur->p_next = ptr->p_next; } else { p_cur->p_next = ptr; p_cur = p_cur->p_next; } build_list(head, p_cur, pnum); } } } //递归反转单链表 void list_reverse(List **head, List *p_cur, List *p_nt, int *pnum) { if (NULL == p_nt) { *head = p_cur; --(*pnum); return ; } list_reverse(head, p_cur->p_next, p_nt->p_next, pnum); p_nt->p_next = p_cur; --(*pnum); if (0 == *pnum) { p_cur->p_next = NULL; } } //递归打印单链表 void print(List *ptr) { if (NULL != ptr) { printf("%d\t", ptr->data); } else { return ; } print(ptr->p_next); }

 

posted on 2012-09-25 13:18  Try86  阅读(1135)  评论(0编辑  收藏  举报