用C语言链表拆分,奇数组成一个链表,偶数组成另外一个链表
时间: 2024-03-13 21:21:02 浏览: 28
```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 = 0; i < n; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = NULL;
if (tail == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
//拆分链表
void splitList(Node* head, Node** oddHead, Node** evenHead) {
Node* oddTail = NULL;
Node* evenTail = NULL;
while (head != NULL) {
Node* node = head;
head = head->next;
node->next = NULL;
if (node->data % 2 == 1) {
if (*oddHead == NULL) {
*oddHead = node;
oddTail = node;
} else {
oddTail->next = node;
oddTail = node;
}
} else {
if (*evenHead == NULL) {
*evenHead = node;
evenTail = node;
} else {
evenTail->next = node;
evenTail = node;
}
}
}
}
//打印链表
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
Node* head = createList(arr, n);
Node* oddHead = NULL;
Node* evenHead = NULL;
splitList(head, &oddHead, &evenHead);
printf("Odd list: ");
printList(oddHead);
printf("Even list: ");
printList(evenHead);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)