将tail定义为node_t **tail, 这种实现精简了不少代码
#include <stdio.h> #include <stdlib.h> #define list_len(a_list) (a_list->cur_num) typedef struct node_s{ int data; struct node_s *next; }node_t; typedef struct list_s{ node_t *head; node_t **tail; int cur_num; }list_t; list_t *list_init(){ list_t *a_list = calloc(1, sizeof(list_t)); if(!a_list){ return NULL; } a_list->head = NULL; a_list->tail = &a_list->head; a_list->cur_num = 0; } int list_insert(list_t *a_list, int data){ node_t *node = calloc(1, sizeof(node_t)); if(!node){ return -1; } node->data = data; *(a_list->tail) = node; a_list->tail = &node->next; a_list->cur_num++; return 0; } void list_print(list_t *a_list){ node_t *node = a_list->head; printf("Total:%d ", list_len(a_list)); while(node){ printf("%d ", node->data); node = node->next; } } int main(){ list_t *a_list = list_init(); int i; for(i=0; i<10; i++){ list_insert(a_list, i); } list_print(a_list); }