c语言单链表节点冒泡排序
时间: 2023-11-23 19:57:57 浏览: 87
用C语言实现单链表的各种操作(二)
以下是C语言单链表节点冒泡排序的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建链表
Node *createList(int arr[], int n) {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
Node *p = head;
for (int i = 0; i < n; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = NULL;
p->next = newNode;
p = p->next;
}
return head;
}
// 打印链表
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 链表节点冒泡排序
void bubbleSort(Node *head) {
Node *p, *q, *tail = NULL;
while (head->next != tail) {
p = head;
q = head->next;
while (q->next != tail) {
if (q->data > q->next->data) {
p->next = q->next;
q->next = q->next->next;
p->next->next = q;
q = p->next;
}
p = p->next;
q = q->next;
}
tail = q;
}
}
// 测试
int main() {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int n = sizeof(arr) / sizeof(int);
Node *head = createList(arr, n);
printf("排序前:");
printList(head);
bubbleSort(head);
printf("排序后:");
printList(head);
return 0;
}
```
阅读全文