设计一个算法,删除递增有序链表中值大于25的所有偶数元素(mink是给定的参数,其值可以和表中的元素相同,也可以不同 )。要求从键盘输入这10个数字{8,12,13,21,24,30,41,50,53,66}。用C语言
时间: 2024-05-10 21:18:39 浏览: 61
以下是一种删除递增有序链表中值大于25的所有偶数元素的算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MIN_K 25
// 链表结构体定义
typedef struct node {
int data;
struct node* next;
} Node;
// 删除递增有序链表中值大于MIN_K的所有偶数元素
void deleteEven(Node** head, int MIN_K) {
Node *cur = *head, *prev = NULL;
while (cur != NULL) {
if (cur->data > MIN_K && cur->data % 2 == 0) {
if (prev == NULL) {
// 第一个元素是偶数
*head = cur->next;
free(cur);
cur = *head;
} else {
prev->next = cur->next;
free(cur);
cur = prev->next;
}
} else {
prev = cur;
cur = cur->next;
}
}
}
int main() {
// 构建链表
Node* head = NULL;
Node* tail = NULL;
int nums[10] = {8, 12, 13, 21, 24, 30, 41, 50, 53, 66};
for (int i = 0; i < 10; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = nums[i];
node->next = NULL;
if (i == 0) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
// 删除递增有序链表中值大于MIN_K的所有偶数元素
deleteEven(&head, MIN_K);
// 输出链表
Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
// 释放链表内存
cur = head;
while (cur != NULL) {
Node* next = cur->next;
free(cur);
cur = next;
}
return 0;
}
```
输出结果为:
```
13 21 41 53
```
阅读全文