用c语言写一个把链表从大到小排序的函数
时间: 2023-05-26 15:07:49 浏览: 55
以下是一个简单的用C语言实现链表从大到小排序的函数:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head, int value)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = value;
new_node->next = (*head);
(*head) = new_node;
}
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
void sortList(struct Node** head)
{
struct Node *current, *next;
int temp;
current = *head;
while (current != NULL) {
next = current->next;
while (next != NULL) {
if (current->data < next->data) {
temp = current->data;
current->data = next->data;
next->data = temp;
}
next = next->next;
}
current = current->next;
}
}
int main()
{
struct Node* head = NULL;
insert(&head, 7);
insert(&head, 9);
insert(&head, 2);
insert(&head, 3);
insert(&head, 6);
insert(&head, 1);
printf("\n Original Linked list: \n");
printList(head);
// Sort the list
sortList(&head);
printf("\n Sorted Linked list: \n");
printList(head);
return 0;
}
```
该程序定义了一个包含`data`和`next`指针的结构体`Node`,该结构体代表链表的节点。然后定义了向链表中插入节点的函数`insert()`和打印链表的函数`printList()`
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)