刚刚在做C语言作业,需要对链表排序,本来想偷懒来CSDN抄一个的,也许是我点背,试了几个都不对,要么是死循环,要么就排序结果根本不对,愤懑之下决定自己用冒泡排序写一个对链表排序的函数分享在这里,希望不要再有人拿着自己错误的代码在这里浪费平台的资源和别人的时间。
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表尾部
void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 输出链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
// 链表排序函数(冒泡排序)
void sortList(struct Node* head) {
struct Node* current;
struct Node* index = NULL;
int temp;
if (head == NULL) {
return;
}
do {
current = head;
while (current->next != index) {
if (current->data > current->next->data) {
// 交换节点数据
temp = current->data;
current->data = current->next->data;
current->next->data = temp;
}
current = current->next;
}
index = current;
} while (index != head->next);
}
// 主函数
int main() {
struct Node* head = NULL;
// 插入节点
insertNode(&head, 5);
insertNode(&head, 3);
insertNode(&head, 8);
insertNode(&head, 1);
insertNode(&head, 6);
// 输出未排序的链表
printf("未排序的链表:\n");
printList(head);
// 对链表进行排序
sortList(head);
// 输出排序后的链表
printf("排序后的链表:\n");
printList(head);
system("pause");
return 0;
}