输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; } 输入输出示例:括号内为说明 输入样例: 1 2 3 4 5 6 7 -1 输出样例: 1 3 5 7 用c语言写代码
时间: 2024-03-25 16:37:24 浏览: 63
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void printList(struct Node *head) {
struct Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void deleteEvenNodes(struct Node *head) {
struct Node *p = head, *q;
while (p != NULL && p->data % 2 == 0) {
head = p->next;
free(p);
p = head;
}
while (p != NULL) {
while (p != NULL && p->data % 2 == 1) {
q = p;
p = p->next;
}
if (p == NULL) break;
q->next = p->next;
free(p);
p = q->next;
}
}
int main() {
int x;
struct Node *head = NULL, *tail = NULL;
while (1) {
scanf("%d", &x);
if (x == -1) break;
struct Node *p = (struct Node *)malloc(sizeof(struct Node));
p->data = x;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
printf("Original list: ");
printList(head);
deleteEvenNodes(head);
printf("List after deleting even nodes: ");
printList(head);
return 0;
}
```
代码的逻辑是先删除头部的所有偶数节点,然后再删除后面的偶数节点。需要注意的是,删除节点时要使用 `free` 函数释放内存,否则会出现内存泄漏的问题。
阅读全文