编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; } 输入输出示例:括号内为说明 输入样例: 1 2 3 4 5 6 7 -1 输出样例: 1 3 5 7 用c语言程序写代码 按照输入和输出要求写并没有格式错误
时间: 2024-03-26 13:40:24 浏览: 12
以下是实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
// 创建链表
struct Node *createLinkedList() {
struct Node *head = NULL, *tail = NULL;
int val;
scanf("%d", &val);
while (val != -1) {
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->data = val;
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
scanf("%d", &val);
}
return head;
}
// 删除偶数节点
struct Node *removeEvenNodes(struct Node *head) {
struct Node *p = head, *prev = NULL;
while (p != NULL) {
if (p->data % 2 == 0) {
if (prev == NULL) {
head = p->next;
} else {
prev->next = p->next;
}
struct Node *tmp = p;
p = p->next;
free(tmp);
} else {
prev = p;
p = p->next;
}
}
return head;
}
// 输出链表
void printLinkedList(struct Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node *head = createLinkedList();
head = removeEvenNodes(head);
printLinkedList(head);
return 0;
}
```