举一个链表排序实例从大向小排用C语言写不能用头结点
时间: 2023-10-09 22:08:14 浏览: 43
好的,这里是一个简单的链表排序实例,使用选择排序算法从大到小排序,使用C语言编写,不使用头结点:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void swap(struct Node* a, struct Node* b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
void selectionSort(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
struct Node* maxNode = current;
struct Node* temp = current->next;
while (temp != NULL) {
if (temp->data > maxNode->data) {
maxNode = temp;
}
temp = temp->next;
}
swap(current, maxNode);
current = current->next;
}
}
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 3;
head->next = second;
second->data = 1;
second->next = third;
third->data = 2;
third->next = NULL;
printf("Original list: ");
printList(head);
selectionSort(head);
printf("Sorted list: ");
printList(head);
return 0;
}
```
该程序首先定义了一个结构体 `Node` 表示链表节点,包含一个整型数据成员 `data` 和一个指向下一个节点的指针成员 `next`。
接着定义了一个 `swap` 函数,用于交换两个节点的数据。
然后定义了一个选择排序的函数 `selectionSort`,该函数使用两个指针 `current` 和 `maxNode` 分别表示当前节点和当前节点之后的最大节点,使用一个循环遍历链表,每次找到当前节点之后的最大节点并交换其数据,直到排序完成。
最后定义了一个打印链表的函数 `printList`,用于输出链表的每个节点的数据。在主函数中创建了一个简单的链表,调用排序函数进行排序,并输出排序后的链表。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)