用C语言编写算法创建以整数为数据元素的单向链表,实现将其分解成两个链表,其中一个全部为奇数,另一个全部为偶数(尽量利用已知的存储空间)。 输入格式: 1 2 3 4 5 6 7 8 9 0 输出格式: 1 3 5 7 9 2 4 6 8
时间: 2024-09-26 22:06:40 浏览: 74
在C语言中,我们可以使用结构体表示链表节点,并定义两个链表分别存储奇数和偶数。以下是实现该功能的基本步骤:
1. 定义链表节点结构体:
```c
typedef struct ListNode {
int data;
struct ListNode* next;
} ListNode;
```
2. 初始化链表函数,接受数组作为输入并构造链表:
```c
ListNode* createList(int arr[], int size) {
ListNode* head = NULL, *tail = NULL;
for (int i = 0; i < size; i++) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->data = arr[i];
newNode->next = NULL;
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
```
3. 分解链表函数,遍历链表并将奇数和偶数分开:
```c
void splitEvenOdd(ListNode* head, ListNode** evenHead, ListNode** oddHead) {
ListNode* even = *evenHead = NULL, *odd = *oddHead = NULL;
while (head != NULL) {
if (head->data % 2 == 0) {
if (!even) {
even = odd = head;
} else {
odd->next = head;
odd = odd->next;
}
} else {
if (!odd) {
odd = head;
} else {
even->next = head;
even = even->next;
}
}
head = head->next;
}
if (odd) odd->next = NULL; // 将奇数链表断开
}
```
4. 输出链表:
```c
void printList(ListNode* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
```
完整代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int data;
struct ListNode* next;
} ListNode;
ListNode* createList(int arr[], int size) {
ListNode* head = NULL, *tail = NULL;
for (int i = 0; i < size; i++) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->data = arr[i];
newNode->next = NULL;
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void splitEvenOdd(ListNode* head, ListNode** evenHead, ListNode** oddHead) {
ListNode* even = *evenHead = NULL, *odd = *oddHead = NULL;
while (head != NULL) {
if (head->data % 2 == 0) {
if (!even) {
even = odd = head;
} else {
odd->next = head;
odd = odd->next;
}
} else {
if (!odd) {
odd = head;
} else {
even->next = head;
even = even->next;
}
}
head = head->next;
}
if (odd) odd->next = NULL;
}
void printList(ListNode* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int size = sizeof(arr) / sizeof(arr[0]);
ListNode* inputList = createList(arr, size);
ListNode* evenList = NULL, *oddList = NULL;
splitEvenOdd(inputList, &evenList, &oddList);
printf("Odd numbers: ");
printList(oddList);
printf("\nEven numbers: ");
printList(evenList);
free(inputList);
return 0;
}
```
阅读全文