编写一个完整的C语言程序,插入单链表5 3 7,以此单链表的首结点值5为基准,将该单链表分割为两部分,使所有小于5的结点排在大于或等于5的结点之前。
时间: 2024-09-28 19:12:43 浏览: 50
在C语言中,我们可以编写以下函数来实现这个功能。首先,我们需要创建一个简单的链表结构,并包含一个辅助函数用于比较节点值,然后实现分割链表的功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 比较函数,用于确定节点是否小于5
int compare(int a, int b) {
return (a < 5) ? -1 : 1; // 如果a小于5返回-1,否则返回1
}
// 插入新节点到链表
void insert(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 分割链表
void splitList(Node** head) {
if (*head == NULL || (*head)->data >= 5) {
return;
}
Node* lessThanFive = *head;
Node* equalOrGreater = (*head)->next;
while (equalOrGreater != NULL && compare(equalOrGreater->data, 5) >= 0) {
lessThanFive = lessThanFive->next;
equalOrGreater = equalOrGreater->next;
}
lessThanFive->next = NULL; // 将小于5的部分断开
(*head)->next = equalOrGreater; // 连接大于等于5的部分到剩余链表
}
// 打印链表
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 插入节点
insert(&head, 5);
insert(&head, 3);
insert(&head, 7);
printf("Original list: ");
printList(head);
// 分割链表
splitList(&head);
printf("Split list: ");
printList(head);
return 0;
}
```
当你运行这个程序,它会先打印原始的链表`5 3 7`,然后分割后变成`5 3 | 7`,其中`|`表示两个链表的分界。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)