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

相关推荐
大白的编程日记.1 小时前
【计算机基础理论知识】C++篇(二)
开发语言·c++·学习
网小鱼的学习笔记1 小时前
python中MongoDB操作实践:查询文档、批量插入文档、更新文档、删除文档
开发语言·python·mongodb
C语言小火车1 小时前
野指针:C/C++内存管理的“幽灵陷阱”与系统化规避策略
c语言·c++·学习·指针
Q_Q5110082851 小时前
python的保险业务管理与数据分析系统
开发语言·spring boot·python·django·flask·node.js·php
亮1111 小时前
Maven 编译过程中发生了 Java Heap Space 内存溢出(OutOfMemoryError)
java·开发语言·maven
凤年徐1 小时前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
Chef_Chen2 小时前
从0开始学习R语言--Day40--Kruskal-Wallis检验
开发语言·学习·r语言
鑫宇吖2 小时前
Polyspace作为MISRA-C合规性检查工具,其检查规则会根据目标C语言标准(C90或C99)动态调整限值要求。
c语言·嵌入式·c99·c90·polyspace·misra-c合规性检查
Zhu_S W2 小时前
深入理解Java虚拟机:Java内存区域与内存溢出异常
java·开发语言·jvm
灰海2 小时前
原型与原型链到底是什么?
开发语言·前端·javascript·es6·原型模式·原生js