单链表的排序,使用冒泡排序【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

相关推荐
消失的旧时光-194332 分钟前
第二十四课:从 Java 后端到系统架构——后端能力体系的最终总结
java·开发语言·系统架构
西门吹-禅35 分钟前
文本搜索node js--meilisearch
开发语言·javascript·ecmascript
Anastasiozzzz1 小时前
G1垃圾回收流程详解
java·开发语言·算法
前路不黑暗@2 小时前
Java项目:Java脚手架项目的通用组件的封装(五)
java·开发语言·spring boot·学习·spring cloud·bootstrap·maven
sa100272 小时前
京东评论接口调用、签名生成与异常处理
开发语言·数据库·python
赵谨言2 小时前
基于Python实现地理空间数据批处理技术探讨及实现--以“多规合一“总体规划数据空间叠加分析为例
大数据·开发语言·经验分享·python
独自破碎E2 小时前
BISHI40数组取精
java·开发语言
丑八怪大丑3 小时前
Java面向对象(进阶)
java·开发语言
java1234_小锋3 小时前
Java高频面试题:Java中变量和常量有什么区别?
java·开发语言·面试
enjoy嚣士3 小时前
Java 之 实现C++库函数等价函数遇到的问题
java·开发语言·c++