#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);
}
用C语言写一个万能单向链表
最新推荐文章于 2024-03-22 20:20:53 发布
该代码示例展示了如何在C语言中定义和操作链表结构,包括初始化、在链表头和尾部添加元素以及删除头尾元素的功能。

1652

被折叠的 条评论
为什么被折叠?



