c语言实现删除单链表min和max之间的节点
时间: 2024-05-05 17:16:12 浏览: 78
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createList(int arr[], int size) {
struct Node* head = NULL;
struct Node* tail = NULL;
for (int i = 0; i < size; i++) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
}
else {
tail->next = node;
tail = node;
}
}
return head;
}
void deleteNodesBetween(struct Node** headRef, int min, int max) {
struct Node* prev = NULL;
struct Node* curr = *headRef;
while (curr != NULL) {
if (curr->data > min && curr->data < max) {
if (prev == NULL) {
*headRef = curr->next;
}
else {
prev->next = curr->next;
}
struct Node* temp = curr;
curr = curr->next;
free(temp);
}
else {
prev = curr;
curr = curr->next;
}
}
}
void printList(struct Node* head) {
for (struct Node* curr = head; curr != NULL; curr = curr->next) {
printf("%d ", curr->data);
}
printf("\n");
}
int main() {
int arr[] = { 1, 5, 3, 6, 2, 4, 7 };
int size = sizeof(arr) / sizeof(arr[0]);
struct Node* head = createList(arr, size);
printf("Original list: ");
printList(head);
deleteNodesBetween(&head, 2, 6);
printf("List after deletion: ");
printList(head);
return 0;
}
```
该程序首先创建一个单链表,然后调用`deleteNodesBetween`函数来删除单链表中值在`min`和`max`之间的节点。该函数使用两个指针`prev`和`curr`来遍历单链表,同时使用条件语句来判断当前节点是否需要被删除。如果需要删除当前节点,则将其从单链表中移除,并释放其内存。最后,程序输出删除节点后的单链表。
阅读全文