C语言使用qsort函数对链表排序
时间: 2023-12-04 15:03:27 浏览: 121
C语言的qsort函数只能对数组进行排序,对于链表的排序可以使用其他算法,比如插入排序或归并排序。
以下是使用插入排序对链表进行排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
} Node;
void insert(Node** head, int value) {
Node* new_node = malloc(sizeof(Node));
new_node->value = value;
new_node->next = *head;
*head = new_node;
}
void print_list(Node* head) {
while (head != NULL) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
}
void insertion_sort(Node** head) {
Node* sorted_list = NULL;
Node* current = *head;
while (current != NULL) {
Node* next = current->next;
if (sorted_list == NULL || current->value < sorted_list->value) {
current->next = sorted_list;
sorted_list = current;
} else {
Node* temp = sorted_list;
while (temp->next != NULL && temp->next->value < current->value) {
temp = temp->next;
}
current->next = temp->next;
temp->next = current;
}
current = next;
}
*head = sorted_list;
}
int main() {
Node* head = NULL;
insert(&head, 5);
insert(&head, 2);
insert(&head, 8);
insert(&head, 1);
insert(&head, 4);
printf("Before sorting: ");
print_list(head);
insertion_sort(&head);
printf("After sorting: ");
print_list(head);
return 0;
}
```
输出结果为:
```
Before sorting: 4 1 8 2 5
After sorting: 1 2 4 5 8
```
阅读全文