输入若干个正整数(输入-1 为结束标志)建立一个单向链表,头指针为 h,输出链表中奇数值的结点。试使用简单的c语言编写相应程序。
时间: 2024-03-07 12:48:39 浏览: 96
以下是简单的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
int num;
struct Node* head = NULL;
struct Node* tail = NULL;
// 输入数据建立链表
printf("请输入若干个正整数(以-1结束):\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = num;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
}
// 输出奇数节点
printf("奇数节点为:\n");
struct Node* p = head;
while (p != NULL) {
if (p->data % 2 == 1) {
printf("%d ", p->data);
}
p = p->next;
}
// 释放内存
p = head;
while (p != NULL) {
struct Node* temp = p;
p = p->next;
free(temp);
}
return 0;
}
```
输入示例:
```
请输入若干个正整数(以-1结束):
1 2 3 4 5 6 7 8 -1
```
输出示例:
```
奇数节点为:
1 3 5 7
```
阅读全文