寻找单链表中奇数并将偶数输出;寻找偶数并将偶数输出 c++代码
时间: 2024-05-10 19:21:02 浏览: 11
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void print_even(Node* head) { // 输出偶数
Node* p = head;
while (p != NULL) {
if (p->data % 2 == 0) {
printf("%d ", p->data);
}
p = p->next;
}
printf("\n");
}
void print_odd(Node* head) { // 输出奇数
Node* p = head;
while (p != NULL) {
if (p->data % 2 == 1) {
printf("%d ", p->data);
}
p = p->next;
}
printf("\n");
}
int main() {
Node* head = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = NULL;
Node* p = head;
for (int i = 2; i <= 10; i++) { // 构造一个1到10的单链表
Node* node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = p->next;
}
print_odd(head); // 输出奇数
print_even(head); // 输出偶数
return 0;
}
```