在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);
}
需要注意的是,链表删除节点时要注意处理头节点和尾节点的情况,以及释放删除节点的内存空间,避免内存泄漏。