2. 写程序对单链表进行排序.
时间: 2023-12-23 14:03:28 浏览: 66
下面是对单链表进行排序的示例程序,使用冒泡排序算法:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建链表
Node *createList(int arr[], int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *p = (Node *) malloc(sizeof(Node));
p->data = arr[i];
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
// 打印链表
void printList(Node *head) {
for (Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->data);
}
printf("\n");
}
// 对链表进行排序
void sortList(Node *head) {
for (Node *p = head; p != NULL; p = p->next) {
for (Node *q = p->next; q != NULL; q = q->next) {
if (p->data > q->data) {
int temp = p->data;
p->data = q->data;
q->data = temp;
}
}
}
}
int main() {
int arr[] = {5, 3, 1, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
Node *head = createList(arr, n);
printf("原始链表:");
printList(head);
sortList(head);
printf("排序后链表:");
printList(head);
return 0;
}
```
程序运行结果如下:
```
原始链表:5 3 1 4 2
排序后链表:1 2 3 4 5
```
阅读全文