c语言单链表冒泡排序
时间: 2023-11-08 16:05:53 浏览: 100
单链表冒泡排序的思路是每次比较相邻两个节点的值,如果前一个节点的值大于后一个节点的值,则交换它们的位置。这样一轮下来,最大的节点就会被排到链表的末尾。然后再从头开始进行下一轮比较,直到所有节点都被排好序为止。
以下是单链表冒泡排序的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void bubbleSort(Node *head) {
if (head == NULL || head->next == NULL) {
return;
}
int swapped;
Node *p, *q = NULL;
do {
swapped = 0;
p = head;
while (p->next != q) {
if (p->data > p->next->data) {
int temp = p->data;
p->data = p->next->data;
p->next->data = temp;
swapped = 1;
}
p = p->next;
}
q = p;
} while (swapped);
}
int main() {
Node *head = NULL, *tail = NULL;
int n, x;
printf("请输入链表长度:");
scanf("%d", &n);
printf("请输入链表元素:");
for (int i = 0; i < n; i++) {
scanf("%d", &x);
Node *node = (Node *)malloc(sizeof(Node));
node->data = x;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
bubbleSort(head);
printf("排序后的链表为:");
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
阅读全文