单链表(指针的指针应用)

将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\n", list_len(a_list));
        while(node){
                printf("%d\n", 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);
}

 

转载于:https://www.cnblogs.com/bai-jimmy/p/5501560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值