用C语言将一个链表分解
时间: 2023-06-14 20:02:48 浏览: 77
我不确定您的问题的具体含义,但我理解您的意思是将一个链表拆分成多个链表。下面是一个示例代码,可以将一个链表按照奇偶性分解成两个链表:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void split_list(Node *head, Node **odd_head, Node **even_head) {
Node *curr = head;
Node *odd_tail = NULL;
Node *even_tail = NULL;
while (curr != NULL) {
if (curr->data % 2 == 0) {
if (*even_head == NULL) {
*even_head = curr;
} else {
even_tail->next = curr;
}
even_tail = curr;
} else {
if (*odd_head == NULL) {
*odd_head = curr;
} else {
odd_tail->next = curr;
}
odd_tail = curr;
}
curr = curr->next;
}
if (odd_tail != NULL) {
odd_tail->next = NULL;
}
if (even_tail != NULL) {
even_tail->next = NULL;
}
}
void print_list(Node *head) {
Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
Node *odd_head = NULL;
Node *even_head = NULL;
// 创建链表
for (int i = 1; i <= 10; i++) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = i;
new_node->next = head;
head = new_node;
}
printf("Original list: ");
print_list(head);
// 拆分链表
split_list(head, &odd_head, &even_head);
printf("Odd list: ");
print_list(odd_head);
printf("Even list: ");
print_list(even_head);
return 0;
}
```
这段代码定义了一个 `Node` 结构体来表示链表中的节点。`split_list()` 函数将给定的链表按照奇偶性分解成两个链表,其中 `odd_head` 和 `even_head` 分别是指向奇数链表和偶数链表的头节点的指针。最后,我们可以使用 `print_list()` 函数来打印原始链表、奇数链表和偶数链表。