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

相关推荐
小白学大数据2 分钟前
Python爬虫如何应对网站的反爬加密策略?
开发语言·爬虫·python
Akiiiira3 分钟前
【数据结构】队列
java·开发语言·数据结构
程序媛学姐9 分钟前
Java级联操作:CascadeType的选择与最佳实践
java·开发语言
LetsonH42 分钟前
Python工具链UV整合环境管理
开发语言·python·uv
zm1 小时前
UDP 多点通信
开发语言·php
.小墨迹2 小时前
Apollo学习——planning模块(3)之planning_base
linux·开发语言·c++·学习·自动驾驶
小喵喵生气气2 小时前
Python60日基础学习打卡D26
开发语言·python
*neverGiveUp*2 小时前
PHP基础知识
开发语言·php
課代表2 小时前
AcroForm JavaScript Promise 对象应用示例: 异步加载PDF文件
开发语言·javascript·pdf·promise·对象
我是Superman丶2 小时前
【Lua】java 调用redis执行 lua脚本
java·开发语言·junit