#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);
}
用C语言写一个万能双向链表
最新推荐文章于 2024-09-11 11:42:14 发布