寻找单链表中奇数并将奇数输出;寻找偶数并将偶数输出。 C语言程序
时间: 2024-05-19 21:14:22 浏览: 88
c代码-5-1随堂while 奇数之和与偶数之和
#include <stdio.h>
#include <stdlib.h>
//定义链表节点
typedef struct node {
int data;
struct node *next;
} Node;
//创建链表
Node *createList(int n) {
Node *head = NULL, *tail = NULL, *p = NULL;
int i, num;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &num);
p = (Node *)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
}
else {
tail->next = p;
tail = p;
}
}
return head;
}
//输出链表
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//输出奇数节点
void printOdd(Node *head) {
Node *p = head;
while (p != NULL) {
if (p->data % 2 != 0) {
printf("%d ", p->data);
}
p = p->next;
}
printf("\n");
}
//输出偶数节点
void printEven(Node *head) {
Node *p = head;
while (p != NULL) {
if (p->data % 2 == 0) {
printf("%d ", p->data);
}
p = p->next;
}
printf("\n");
}
int main() {
int n;
Node *head = NULL;
printf("请输入链表的节点个数:");
scanf("%d", &n);
head = createList(n);
printf("链表的值为:");
printList(head);
printf("奇数节点的值为:");
printOdd(head);
printf("偶数节点的值为:");
printEven(head);
return 0;
}
阅读全文