基本数据结构--链表示例代码

#include <stdio.h> 
#include <stdlib.h> 
 
// 定义链表节点结构 
typedef struct Node { 
    void *data; 
    struct Node *next; 
} Node; 
 
// 定义链表结构 
typedef struct List { 
    Node *head; 
} List; 
 
// 创建一个新节点 
Node* createNode(void *data) { 
    Node *newNode = (Node*)malloc(sizeof(Node)); 
    if (newNode == NULL) { 
        fprintf(stderr, "内存分配失败\n"); 
        exit(EXIT_FAILURE); 
    } 
    newNode->data = data; 
    newNode->next = NULL; 
    return newNode; 
} 
 
// 初始化链表 
List* createList() { 
    List *newList = (List*)malloc(sizeof(List)); 
    if (newList == NULL) { 
        fprintf(stderr, "内存分配失败\n"); 
        exit(EXIT_FAILURE); 
    } 
    newList->head = NULL; 
    return newList; 
} 
 
// 在链表头部插入节点 
void insertAtHead(List *list, void *data) { 
    Node *newNode = createNode(data); 
    newNode->next = list->head; 
    list->head = newNode; 
} 
 
// 遍历链表并执行回调函数 
void traverseList(List *list, void (*callback)(void *)) { 
    Node *current = list->head; 
    while (current!= NULL) { 
        callback(current->data); 
        current = current->next; 
    } 
} 
 
// 释放链表内存 
void freeList(List *list) { 
    Node *current = list->head; 
    Node *nextNode; 
    while (current!= NULL) { 
        nextNode = current->next; 
        free(current->data);  // 这里假设data是通过malloc分配的,需要释放 
        free(current); 
        current = nextNode; 
    } 
    free(list); 
} 
// 示例回调函数,用于打印整数 
void printInt(void *data) { 
    int *num = (int *)data; 
    printf("%d ", *num); 
} 
 
int main() { 
    List *list = createList(); 
    
    // 插入一些整数 
    int num1 = 10; 
    int num2 = 20; 
    int num3 = 30; 
    
    insertAtHead(list, &num1); 
    insertAtHead(list, &num2); 
    insertAtHead(list, &num3); 
    
    // 遍历链表并打印数据 
    printf("链表中的数据: "); 
    traverseList(list, printInt); 
    printf("\n"); 
    
    // 释放链表内存 
    freeList(list); 
    
    return 0; 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

和风化雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值