写一个c语言单链表冒泡跑许
时间: 2023-08-25 20:12:44 浏览: 128
下面是单链表冒泡排序的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 冒泡排序函数
struct ListNode* bubbleSortList(struct ListNode* head) {
// 如果链表为空或只有一个节点,直接返回
if (!head || !head->next) {
return head;
}
// 冒泡排序
struct ListNode *cur = head, *tail = NULL;
while (tail != head->next) {
while (cur->next != tail) {
if (cur->val > cur->next->val) {
int temp = cur->val;
cur->val = cur->next->val;
cur->next->val = temp;
}
cur = cur->next;
}
tail = cur;
cur = head;
}
return head;
}
// 创建链表函数
struct ListNode* createList(int *arr, int size) {
struct ListNode *head = NULL, *tail = NULL;
for (int i = 0; i < size; i++) {
struct ListNode *newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = arr[i];
newNode->next = NULL;
if (!head) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 打印链表函数
void printList(struct ListNode *head) {
struct ListNode *cur = head;
while (cur) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
int arr[] = {5, 3, 8, 1, 6};
int size = sizeof(arr) / sizeof(arr[0]);
struct ListNode *head = createList(arr, size);
printf("排序前:");
printList(head);
head = bubbleSortList(head);
printf("排序后:");
printList(head);
return 0;
}
```
这个代码使用了链表的基本操作,包括创建链表、打印链表和节点交换等。可以看到,C语言的链表操作比较繁琐,但是也比较灵活,适用于一些特殊的场景。
阅读全文