c语言写一算法,删除单链表中值为key的所有节点
时间: 2024-09-24 09:13:13 浏览: 73
在C语言中,删除单链表中所有值为`key`的节点,你可以编写如下的算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 定义辅助函数用于查找并替换节点
Node* find_and_replace(Node* head, int key, int new_val) {
if (head == NULL) return NULL;
if (head->data == key) {
head->data = new_val;
return head;
}
Node* current = head->next;
while (current != NULL) {
if (current->data == key) {
current->data = new_val;
}
current = current->next;
}
return head;
}
// 删除所有值为key的节点
void remove_all_nodes(Node** head, int key) {
Node* temp = *head;
Node* prev = NULL;
while (temp != NULL) {
if (temp->data == key) {
if (prev == NULL) { // 删除头节点的情况
*head = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
temp = *head; // 更新临时指针,继续遍历
} else {
prev = temp;
temp = temp->next;
}
}
}
// 示例
void print_list(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
Node* list = create_linked_list(); // 这里假设你已经创建了一个链表
printf("Original List: \n");
print_list(list);
remove_all_nodes(&list, 5); // 删除值为5的节点
printf("List after removing nodes with value 5: \n");
print_list(list);
return 0;
}
阅读全文