Update README.md

This commit is contained in:
Jdhggg 2025-03-17 15:01:17 +08:00
parent fb1e08c1a0
commit e275251e3a

106
README.md
View File

@ -9,17 +9,23 @@
#ifndef LINKED_LIST_H #ifndef LINKED_LIST_H
#define LINKED_LIST_H #define LINKED_LIST_H
#include <stdbool.h>
// 链表节点结构体
typedef struct Node { typedef struct Node {
int data; int data;
struct Node* next; struct Node* next;
} Node; } Node;
Node* createNode(int data); // 链表操作函数声明
void insertNode(Node** head, int data); Node* create_node(int data);
void deleteNode(Node** head, int data); void append_node(Node** head, int data);
void printList(Node* head); bool delete_node(Node** head, int data);
void print_list(const Node* head);
void free_list(Node** head);
#endif // LINKED_LIST_H
#endif
``` ```
`linked_list.c`: `linked_list.c`:
@ -28,39 +34,83 @@ void printList(Node* head);
#include <stdlib.h> #include <stdlib.h>
#include "linked_list.h" #include "linked_list.h"
Node* createNode(int data) { // 创建新节点
Node* newNode = (Node*)malloc(sizeof(Node)); Node* create_node(int data) {
newNode->data = data; Node* new_node = (Node*)malloc(sizeof(Node));
newNode->next = NULL; if (!new_node) {
return newNode; fprintf(stderr, "内存分配失败\n");
exit(EXIT_FAILURE);
}
new_node->data = data;
new_node->next = NULL;
return new_node;
} }
void insertNode(Node** head, int data) { // 在链表末尾添加节点
Node* newNode = createNode(data); void append_node(Node** head, int data) {
newNode->next = *head; Node* new_node = create_node(data);
*head = newNode; if (*head == NULL) {
*head = new_node;
return;
}
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
} }
void deleteNode(Node** head, int data) { // 删除包含指定数据的节点
Node* temp = *head, *prev = NULL; bool delete_node(Node** head, int data) {
while (temp != NULL && temp->data != data) { if (*head == NULL) {
prev = temp; return false;
temp = temp->next;
} }
if (temp == NULL) return; Node* current = *head;
if (prev) prev->next = temp->next; Node* previous = NULL;
else *head = temp->next;
free(temp); // 查找要删除的节点
while (current != NULL && current->data != data) {
previous = current;
current = current->next;
} }
void printList(Node* head) { // 未找到节点
Node* temp = head; if (current == NULL) {
while (temp) { return false;
printf("%d -> ", temp->data); }
temp = temp->next;
// 删除节点
if (previous == NULL) {
// 要删除的是头节点
*head = current->next;
} else {
previous->next = current->next;
}
free(current);
return true;
}
// 打印链表
void print_list(const Node* head) {
const Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
} }
printf("NULL\n"); printf("NULL\n");
} }
// 释放链表内存
void free_list(Node** head) {
Node* current = *head;
while (current != NULL) {
Node* next = current->next;
free(current);
current = next;
}
*head = NULL;
}
``` ```
`main.c`: `main.c`:
```c ```c