在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語言中的鏈表。