编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; } 输入输出示例:括号内为说明 输入样例: 1 2 3 4 5 6 7 -1 输出样例: 1 3 5 7 用c语言程序写代码
时间: 2024-03-22 22:41:08 浏览: 21
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void deleteEvenNodes(struct Node **head) {
struct Node *prev = NULL;
struct Node *curr = *head;
while (curr != NULL) {
if (curr->data % 2 == 0) {
if (prev == NULL) {
*head = 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) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node *head = NULL;
int num;
printf("请输入若干个正整数,以-1结束:\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
deleteEvenNodes(&head);
printf("删除偶数结点后的链表为:\n");
printList(head);
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)