C语言链表把链表的值按照奇数偶数分成俩个
时间: 2024-03-13 08:18:01 浏览: 15
链表,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
void splitList(struct node* head, struct node** oddList, struct node** evenList) {
struct node* odd = NULL;
struct node* even = NULL;
while (head != NULL) {
if (head->data % 2 == 0) {
if (even == NULL) {
even = head;
*evenList = even;
} else {
even->next = head;
even = even->next;
}
} else {
if (odd == NULL) {
odd = head;
*oddList = odd;
} else {
odd->next = head;
odd = odd->next;
}
}
head = head->next;
}
if (even != NULL) {
even->next = NULL;
}
if (odd != NULL) {
odd->next = NULL;
}
}
void printList(struct node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct node* head = NULL;
struct node* oddList = NULL;
struct node* evenList = NULL;
// create a linked list
head = (struct node*)malloc(sizeof(struct node));
head->data = 1;
head->next = (struct node*)malloc(sizeof(struct node));
head->next->data = 2;
head->next->next = (struct node*)malloc(sizeof(struct node));
head->next->next->data = 3;
head->next->next->next = (struct node*)malloc(sizeof(struct node));
head->next->next->next->data = 4;
head->next->next->next->next = NULL;
printf("Original List: ");
printList(head);
splitList(head, &oddList, &evenList);
printf("Odd List: ");
printList(oddList);
printf("Even List: ");
printList(evenList);
return 0;
}
```
输出:
```
Original List: 1 2 3 4
Odd List: 1 3
Even List: 2 4
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)