用链表实现冒泡排序!

本文探讨了如何在不使用数组的情况下,通过链表来实现经典的冒泡排序算法,介绍了链表冒泡排序的实现思路。

一、问题描述

存储数据不仅数组可以,链表也行。那么如何用链表实现冒泡排序呢?

我们需要把数据存储在链表中,然后调用排序函数就可以了。但必须要注意链表与数组的不同点,链表没有下标,要想访问数据域必须通过节点来访问。

二、代码实现
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;

typedef struct Node
{
	ElemType pData;
	Node* pNext;
}Node,*pList;

void Init(pList* ihead)
{
	*ihead = (pList)malloc(sizeof(Node));
	if (*ihead == NULL)exit(0);
	(*ihead)->pNext = NULL;
	(*ihead)->pData = 0;
}
void Insert(pList head, ElemType val)
{
	pList pCur = head;
	for (int i = 0; i < head->pData; ++i)
	{
		pCur = pCur->pNext;
	}
	pList newNode = (pList)malloc(sizeof(Node));
	newNode->pData = val;
	newNode->pNext = NULL;
	pCur->pNext = newNode;
使用链表实现冒泡排序,基本思想与数组的冒泡排序类似,都是通过多次遍历链表,比较相邻节点的值,若顺序错误则交换它们,直到整个链表有序。以下是根据提供的代码示例,详细说明链表实现冒泡排序的方法: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int elem; struct Node* next; } linkedList; // 冒泡排序函数 void bubbleSort(linkedList *&l, int n) { linkedList *head, *first, *temp; for (int i = 0; i < n - 1; i++) { head = l; first = l->next; for (int j = 0; j < n - i - 1; j++) { if (first->elem > first->next->elem) { temp = first->next; first->next = first->next->next; head->next = temp; temp->next = first; head = temp; } else { head = head->next; first = first->next; } } } } // 打印链表函数 void printList(linkedList *l) { linkedList *current = l->next; while (current != NULL) { printf("%d ", current->elem); current = current->next; } printf("\n"); } // 创建新节点函数 linkedList* createNode(int value) { linkedList* newNode = (linkedList*)malloc(sizeof(linkedList)); newNode->elem = value; newNode->next = NULL; return newNode; } int main() { // 创建链表头节点 linkedList* head = (linkedList*)malloc(sizeof(linkedList)); head->next = NULL; // 插入一些测试数据 linkedList* current = head; int values[] = {5, 3, 8, 4, 2}; int n = sizeof(values) / sizeof(values[0]); for (int i = 0; i < n; i++) { current->next = createNode(values[i]); current = current->next; } // 打印排序前的链表 printf("排序前的链表: "); printList(head); // 进行冒泡排序 bubbleSort(head, n); // 打印排序后的链表 printf("排序后的链表: "); printList(head); return 0; } ``` 上述代码通过 `bubbleSort` 函数实现链表冒泡排序。在 `bubbleSort` 函数中,外层循环控制排序的轮数,内层循环用于比较相邻节点并交换位置。`printList` 函数用于打印链表元素,`createNode` 函数用于创建新的链表节点。在 `main` 函数中,创建了一个测试链表,调用 `bubbleSort` 函数进行排序,并打印排序前后的链表元素。
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值