构造一个单链表,寻找单链表中的奇数并将奇数输出,寻找偶数并将偶数输出
时间: 2023-04-04 18:01:47 浏览: 97
好的,这是一个关于单链表的问题。我们可以遍历单链表,判断每个节点的值是奇数还是偶数,然后将其输出。具体实现可以使用一个指针指向单链表的头节点,然后依次遍历每个节点,判断节点的值是奇数还是偶数,然后输出。代码实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 构造单链表
Node* createList(int arr[], int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = ; i < n; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 寻找单链表中的奇数并将奇数输出
void printOdd(Node* head) {
Node* p = head;
while (p != NULL) {
if (p->data % 2 == 1) {
printf("%d ", p->data);
}
p = p->next;
}
}
// 寻找单链表中的偶数并将偶数输出
void printEven(Node* head) {
Node* p = head;
while (p != NULL) {
if (p->data % 2 == ) {
printf("%d ", p->data);
}
p = p->next;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr) / sizeof(arr[]);
Node* head = createList(arr, n);
printf("奇数:");
printOdd(head);
printf("\n偶数:");
printEven(head);
return ;
}
```
输出结果为:
```
奇数:1 3 5 7 9
偶数:2 4 6 8
```
阅读全文
相关推荐

















