用C语言写一个通用链表文件
时间: 2023-05-22 15:05:06 浏览: 68
非常感谢您的提问,以下是用 C 语言编写一个通用链表文件的代码:
```
// 定义链表结构体及节点结构体
typedef struct Node {
void *data; // 存储任意类型的指针
struct Node *next;
} Node;
typedef struct LinkedList {
int size; // 记录链表长度
Node *head;
} LinkedList;
// 初始化链表
LinkedList *newLinkedList() {
LinkedList *list = malloc(sizeof(LinkedList));
list->size = 0;
list->head = NULL;
return list;
}
// 在链表尾部添加节点
void addNode(LinkedList *list, void *data) {
Node *newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
} else {
Node *node = list->head;
while (node->next != NULL) {
node = node->next;
}
node->next = newNode;
}
list->size++;
}
// 根据索引获取节点中的数据
void *getData(LinkedList *list, int index) {
if (index < 0 || index >= list->size) {
return NULL;
}
Node *node = list->head;
for (int i = 0; i < index; i++) {
node = node->next;
}
return node->data;
}
// 释放链表空间
void freeLinkedList(LinkedList *list) {
Node *node = list->head;
while (node != NULL) {
Node *nextNode = node->next;
free(node);
node = nextNode;
}
free(list);
}
```
希望这段代码对您有所帮助!如果您还有其它问题,我将一如既往地竭尽所能地回答。