在C語言中,鏈表刪除節點的方法有以下幾種:
void deleteNode(struct Node** head_ref, int key) {
struct Node* temp = *head_ref;
struct Node* prev = NULL;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
free(temp);
}
void deleteNode(struct Node** head_ref, int key) {
struct Node* temp = *head_ref;
struct Node* prev = NULL;
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
if (prev == NULL) {
*head_ref = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
}
需要注意的是,鏈表刪除節點時要注意處理頭節點和尾節點的情況,以及釋放刪除節點的內存空間,避免內存泄漏。