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

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

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

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

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

// 向链表头部添加元素
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->prev = newNode->next = NULL;
    } else {
        newNode->next = list->head;
        list->head->prev = newNode;
        list->head = newNode;
        newNode->prev = NULL;
    }
}

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

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

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

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

    deleteHead(&list);  
    deleteTail(&list);
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值