用C语言编写,删除递增有序链表中值大于25的所有偶数元素,要求从键盘输入这10个数字{8,12,13,21,24,30,41,50,53,66}
时间: 2024-01-13 13:02:21 浏览: 80
下面是一个基于单向链表的实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* deleteEvenElements(struct ListNode* head, int threshold) {
struct ListNode dummy;
dummy.next = head;
struct ListNode *prev = &dummy;
struct ListNode *cur = head;
while (cur != NULL) {
if (cur->val > threshold && cur->val % 2 == 0) {
prev->next = cur->next;
free(cur);
cur = prev->next;
} else {
prev = cur;
cur = cur->next;
}
}
return dummy.next;
}
void printList(struct ListNode *head) {
while (head != NULL) {
printf("%d->", head->val);
head = head->next;
}
printf("NULL\n");
}
int main() {
int data[] = {8, 12, 13, 21, 24, 30, 41, 50, 53, 66};
int n = sizeof(data) / sizeof(int);
struct ListNode *head = NULL;
for (int i = n - 1; i >= 0; i--) {
struct ListNode *newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = data[i];
newNode->next = head;
head = newNode;
}
printf("Before deletion:\n");
printList(head);
head = deleteEvenElements(head, 25);
printf("After deletion:\n");
printList(head);
return 0;
}
```
输出结果:
```
Before deletion:
8->12->13->21->24->30->41->50->53->66->NULL
After deletion:
13->21->24->41->53->NULL
```
阅读全文