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

相关推荐
Adellle1 分钟前
Java 异步回调
java·开发语言·多线程
海寻山2 分钟前
Java常用API详解(二):集合类API(ArrayList/HashMap/HashSet)实战,一篇吃透
开发语言·python
XMYX-02 分钟前
19 - Go 并发限制:限流与控制并发数
开发语言·golang
qeen873 分钟前
【算法笔记】差分与经典例题解析
c语言·c++·笔记·学习·算法·差分
卵男(章鱼)9 分钟前
汽车网络通讯分析与仿真工具的系统工程:Vector CANoe与ZLG ZCANPRO深度剖析
开发语言·汽车·php
摇滚侠14 分钟前
Java 零基础全套视频教程,面向对象(进阶),笔记 90-103
java·开发语言·笔记
say_fall14 分钟前
红黑树底层原理全解析:从 5 大性质到 STL 容器底层实现
开发语言·c++
椰羊~王小美15 分钟前
C、Java、Go、Python 对比
java·c语言
青槿吖17 分钟前
Sentinel 进阶实战:Feign 整合 + 全局异常 + Nacos 持久化,生产环境直接用
java·开发语言·spring cloud·微服务·云原生·ribbon·sentinel
疯狂打码的少年18 分钟前
内存管理三雄对决:C、Java、Python 的堆区、栈区、常量区、静态区深度解析
java·c语言·python