用C语言写一个万能单向链表

该代码示例展示了如何在C语言中定义和操作链表结构,包括初始化、在链表头和尾部添加元素以及删除头尾元素的功能。
#include <stdio.h>
#include <stdlib.h>

// 结点结构体 
typedef struct Node {
    void *data;      // void指针,可以存储任意类型数据
    struct Node *next; 
} Node;

// 链表结构体
typedef struct List {
    Node *head;
    Node *tail;
} List;

// 初始化链表 
void initList(List *list) {
    list->head = list->tail = NULL;
}

// 向链表尾部添加元素
void addTail(List *list, void *data) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    
    if (list->tail == NULL) {
        list->head = list->tail = newNode;
    } else {
        list->tail->next = newNode;
        list->tail = newNode;
    }
}

// 向链表头部添加元素
void addHead(List *list, void *data) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    
    if (list->head == NULL) {
        list->head = list->tail = newNode;
        newNode->next = NULL;
    } else {
        newNode->next = list->head;
        list->head = newNode;
    }
}

// 删除链表头部元素
void deleteHead(List *list) {
    if (list->head == NULL) return;
    
    Node *next = list->head->next;
    free(list->head);
    list->head = next;
}

// 删除链表尾部元素 
void deleteTail(List *list) {
    if (list->head == NULL) return;
    
    Node *cur = list->head;
    Node *pre = cur;
    
    while (cur->next != NULL) {
        pre = cur;
        cur = cur->next;
    }
    
    free(cur);
    pre->next = NULL;
    list->tail = pre;
}

int main() {
    List list;
    initList(&list);
    
    addTail(&list, "a");
    addTail(&list, "b");
    addHead(&list, "c");
    
    deleteHead(&list);
    deleteTail(&list);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值