编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; }用c语言写代码
时间: 2024-03-26 13:40:47 浏览: 117
好的,以下是C语言代码实现:
```
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void deleteEvenNodes(struct Node** headRef){
struct Node* current = *headRef;
struct Node* prev = NULL;
while(current != NULL){
if(current->data % 2 == 0){
if(prev == NULL){
*headRef = current->next;
free(current);
current = *headRef;
}
else{
prev->next = current->next;
free(current);
current = prev->next;
}
}
else{
prev = current;
current = current->next;
}
}
}
void printList(struct Node* head){
struct Node* current = head;
while(current != NULL){
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main(){
struct Node* head = NULL;
struct Node* tail = NULL;
int data;
printf("请输入若干个正整数,以-1结束:\n");
scanf("%d", &data);
while(data != -1){
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
tail = newNode;
}
else{
tail->next = newNode;
tail = newNode;
}
scanf("%d", &data);
}
deleteEvenNodes(&head);
printList(head);
return 0;
}
```
输入样例:
```
请输入若干个正整数,以-1结束:
1 2 3 4 5 6 -1
```
输出样例:
```
1 3 5
```
阅读全文