输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; } 输入输出示例:括号内为说明 输入样例: 1 2 3 4 5 6 7 -1 输出样例: 1 3 5 7 严格按照要求写代码并且满足输入和输出要求格式,用c语言程序写代码
时间: 2024-03-25 09:37:44 浏览: 15
```
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
int main(){
struct Node *head = NULL, *tail = NULL; // 定义链表头尾指针
int num;
printf("请输入若干个正整数,以-1结束:\n");
scanf("%d", &num);
while(num != -1){
struct Node *newnode = (struct Node*)malloc(sizeof(struct Node)); // 创建新节点
newnode->data = num;
newnode->next = NULL;
if(head == NULL){
head = tail = newnode;
}
else{
tail->next = newnode;
tail = newnode;
}
scanf("%d", &num);
}
struct Node *p = head, *q = NULL; // p指向当前节点,q指向当前节点的前一个节点
while(p != NULL){
if(p->data % 2 == 0){ // 删除偶数节点
if(p == head){
head = head->next;
}
else{
q->next = p->next;
}
struct Node *temp = p;
p = p->next;
free(temp);
}
else{
q = p;
p = p->next;
}
}
printf("删除偶数节点后的链表为:\n");
p = head;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)