在C语言中,链表是一种基本的数据结构,用于存储一系列元素
typedef struct Node {
int data; // 数据域,根据实际需求可以更改为其他类型
struct Node* next; // 指向下一个节点的指针
} Node;
Node* create_node(int data) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void insert_head(Node** head, int data) {
Node* new_node = create_node(data);
new_node->next = *head;
*head = new_node;
}
void delete_node(Node** head, int data) {
Node* current = *head;
Node* previous = NULL;
if (current != NULL && current->data == data) {
*head = current->next;
free(current);
return;
}
while (current != NULL && current->data != data) {
previous = current;
current = current->next;
}
if (current == NULL) {
return; // 没有找到指定值的节点
}
previous->next = current->next;
free(current);
}
void traverse(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
void free_list(Node* head) {
Node* current = head;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
}
遵循这些最佳实践,可以帮助您更有效地操作C语言中的链表。