单链表的排序,使用冒泡排序【c语言】

c 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
	int data;
	struct Node* next;
} Node, *LinkedList;

// 创建一个新节点
Node* createNode(int data) {
	Node* newNode = (Node*)malloc(sizeof(Node));
	if (newNode == NULL) {
		printf("Error! Unable to create a new node.\n");
		exit(0);
	}
	newNode->data = data;
	newNode->next = NULL;
	return newNode;
}

// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
	if (*head == NULL) {
		*head = createNode(data);
	}
	else {
		Node* lastNode = *head;
		while (lastNode->next != NULL) {
			lastNode = lastNode->next;
		}
		lastNode->next = createNode(data);
	}
}

// 打印链表
void printList(LinkedList head) {
	while (head != NULL) {
		printf("%d ", head->data);
		head = head->next;
	}
	printf("\n");
}

int getListLength(Node* node)
{
	int length = 0;
	Node *tail = node;
	while (node != NULL)
	{
		node = node->next;
		length++;
	}
	return length;
}

LinkedList reverseList(Node* head)
{
	Node* pre = NULL;
	Node* cur = head;
	while (cur != NULL)
	{
		Node* temp = cur->next;
		cur->next = pre;
		pre = cur;
		cur = temp;
	}
	return pre;
}

//冒泡排序
void bubbleSort(Node* head1)
{
	Node* i = NULL;
	Node* j = NULL;
	for (i = head1; i != NULL; i = i->next)
	{
		for (j = i->next; j != NULL; j = j->next)
		{
			if (i->data > j->data)
			{
				int temp = i->data;
				i->data = j->data;
				j->data = temp;
			}
		}
	}
}

int main() {
	LinkedList head1 = NULL;
	append(&head1, 1);
	append(&head1, 3);
	append(&head1, 2);
	append(&head1, 6);

	bubbleSort(head1);

	printf("list :  \n");
	printList(head1);
	system("pause");
	return 0;
}

参考:https://blog.csdn.net/m0_72983118/article/details/128068313

相关推荐
明洞日记6 分钟前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
kingmax5421200822 分钟前
《数据结构C语言:单向链表-链表基本操作(尾插法建表、插入)》15分钟试讲教案【模版】
c语言·数据结构·链表
jllllyuz1 小时前
matlab使用B样条进行曲线曲面拟合
开发语言·matlab
ku_code_ku1 小时前
python bert_score使用本地模型的方法
开发语言·python·bert
小马哥编程1 小时前
【软考架构】滑动窗口限流算法的原理是什么?
java·开发语言·架构
云栖梦泽1 小时前
鸿蒙数据持久化实战:构建本地存储与云同步系统
开发语言·鸿蒙系统
wjs20242 小时前
《Ionic 侧栏菜单》
开发语言
祁思妙想2 小时前
linux常用命令
开发语言·python
mit6.8242 小时前
[box64] 解决ARM64运行x86_64跨平台兼容性 | 机器架构配置
c语言
IMPYLH2 小时前
Lua 的 IO (输入/输出)模块
开发语言·笔记·后端·lua