能一个C语言链表排序的demo吗
时间: 2023-03-29 08:01:05 浏览: 93
c语言中用链表实现的排序
可以,以下是一个简单的链表排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void swap(Node* a, Node* b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
void bubbleSort(Node* head) {
int swapped;
Node* ptr1;
Node* lptr = NULL;
if (head == NULL) {
return;
}
do {
swapped = ;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data > ptr1->next->data) {
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
int main() {
Node* head = NULL;
insert(&head, 5);
insert(&head, 3);
insert(&head, 8);
insert(&head, 1);
insert(&head, 6);
printf("Before sorting: ");
printList(head);
bubbleSort(head);
printf("After sorting: ");
printList(head);
return ;
}
```
这个示例代码演示了如何使用冒泡排序算法对链表进行排序。
阅读全文