设在一个头结点的单链表中所有元素结点的数值无序,试编写一个函数,删除表中所有介于给定的两个值(作为函数参数给出)之间的元素结点(若结点存在)。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 插入节点函数
void insertNode(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 打印链表函数
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
puts("NULL");
}
// 删除指定范围内的节点函数
void deleteBetween(Node** head, int low, int high) {
Node* current = *head;
Node* prev = NULL;
// 遍历链表
while (current != NULL) {
if (low <= current->data && current->data <= high) { // 当前节点值在范围内
prev->next = current->next; // 跳过此节点
free(current); // 释放当前节点内存
current = prev->next; // 移动到下一个节点
} else {
prev = current; // 如果不在范围内,则移动prev指针
current = current->next;
}
}
}
int main() {
Node* head = NULL;
// 初始化链表
insertNode(&head, 5);
insertNode(&head, 2);
insertNode(&head, 8);
insertNode(&head, 3);
insertNode(&head, 6);
insertNode(&head, 9);
printf("原始链表为: ");
printList(head);
int lowValue = 3;
int highValue = 7;
printf("刪除%d和%d之间的节点后为: ", lowValue, highValue);
deleteBetween(&head, lowValue, highValue);
printList(head);
return 0;
}