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

相关推荐
灰海5 分钟前
原型与原型链到底是什么?
开发语言·前端·javascript·es6·原型模式·原生js
鸡蛋灌Bean22 分钟前
Java常用设计模式大全
java·开发语言·设计模式
钮钴禄·爱因斯晨35 分钟前
C语言 | 函数核心机制深度解构:从底层架构到工程化实践
c语言·开发语言·数据结构
wkj00137 分钟前
php中array($this, ‘loadClass‘)表示啥意思?
android·开发语言·php
Stuomasi_xiaoxin37 分钟前
服务器重装后如何“复活”旧硬盘上的 Anaconda 环境?—— 一次完整的排错与恢复记录
开发语言·python·github
presenttttt1 小时前
用Python和OpenCV从零搭建一个完整的双目视觉系统(四)
开发语言·python·opencv·计算机视觉
爱学习的小邓同学1 小时前
数据结构 --- 队列
c语言·数据结构
每日出拳老爷子1 小时前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
半桔1 小时前
【Linux手册】从接口到管理:Linux文件系统的核心操作指南
android·java·linux·开发语言·面试·系统架构
nightunderblackcat2 小时前
新手向:实现ATM模拟系统
java·开发语言·spring boot·spring cloud·tomcat·maven·intellij-idea