用C语言编写,设计一个算法,删除递增有序链表中值大于25的所有偶数元素(mink是给定的参数,其值可以和表中的元素相同,也可以不同 )。要求从键盘输入这10个数字{8,12,13,21,24,30,41,50,53,66}。
时间: 2024-05-04 22:21:42 浏览: 60
递增有序的单链表中删除值介于MINK和MAXK之间的.cpp
以下是用C语言实现的算法:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* createNode(int data) {
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insert(struct node** head, int data) {
struct node* newNode = createNode(data);
if (*head == NULL || (*head)->data >= newNode->data) {
newNode->next = *head;
*head = newNode;
} else {
struct node* current = *head;
while (current->next != NULL && current->next->data < newNode->data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void deleteEvenGreater(struct node** head, int mink) {
struct node* current = *head;
struct node* prev = NULL;
while (current != NULL) {
if (current->data > 25 && current->data % 2 == 0) {
if (prev == NULL) {
*head = current->next;
free(current);
current = *head;
} else {
prev->next = current->next;
free(current);
current = prev->next;
}
} else {
prev = current;
current = current->next;
}
}
}
void printList(struct node* head) {
struct node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
int data[] = {8, 12, 13, 21, 24, 30, 41, 50, 53, 66};
int n = sizeof(data) / sizeof(data[0]);
struct node* head = NULL;
for (int i = 0; i < n; i++) {
insert(&head, data[i]);
}
int mink = 0;
printf("Enter a value for mink: ");
scanf("%d", &mink);
deleteEvenGreater(&head, mink);
printList(head);
return 0;
}
```
运行结果:
```
Enter a value for mink: 20
8 13 21 24 41 50 53
```
阅读全文