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

相关推荐
cici1587410 分钟前
MATLAB/Simulink单相光伏并网逆变器仿真
开发语言·matlab
Dev7z12 分钟前
基于MATLAB小波分析的图像增强算法及其仿真实现
开发语言·matlab
代码游侠15 分钟前
学习笔记——栈
开发语言·数据结构·笔记·学习·算法
编程修仙21 分钟前
第七篇 java的注解以及使用反射实现自定义注解功能
xml·java·开发语言·spring
qq_73917536924 分钟前
开源基于STC8的智能浇花与温湿度报警系统
c语言·stm32·单片机·嵌入式硬件
GesLuck34 分钟前
Beaglebone BB Black C版 AM3358(一)
c语言·开发语言·物联网·硬件架构
lusasky35 分钟前
Java内存堆栈AI分析工具全览
java·开发语言
CoderYanger36 分钟前
C.滑动窗口-越长越合法/求最短/最小——2904. 最短且字典序最小的美丽子字符串
java·开发语言·数据结构·算法·leetcode·1024程序员节
QQ_4376643141 小时前
常见题目及答案
android·java·开发语言
hefaxiang1 小时前
C语言数据类型和变量(上)
c语言·开发语言