单向链表的冒泡排序

这篇博客介绍了如何使用C++实现单向链表的冒泡排序。通过`list_create`函数创建链表,然后用`list_sort`进行排序。排序过程中,遍历链表并比较相邻节点值,当需要交换时进行交换。最后在`main`函数中展示排序后的结果。
摘要由CSDN通过智能技术生成
#include <stdio.h>
#include <malloc.h>
#include <iostream>
struct node {
int val;
struct node *next;
};
static void list_sort(struct node *head);
struct node *list_create(int arr[], int size)
{
struct node *head = NULL;
int i;
for (i = size - 1; i >= 0; --i) {
struct node *p = (struct node *)malloc(sizeof(struct node));
p->val = arr[i];
p->next = head;
head = p;
}
return head;
}
void list_sort(struct node *head)
{
node* head2 = head;
node* head1 = head;//此指针用于计数
int size_ = 1;
while (head1->next != NULL)
{
head1 = head1->next;
++size_;                     //输出的为节点个数
}//while
for (int i = size_; i >= 2; --i)
{
for (int j = 1; j<i; ++j)
{
if (head->val > head->next->val)
{
int temple;
temple = head->val;
head->val = head->next->val;
head->next->val = temple;
}//if
head = head->next;//指向下一个节点
}//for
head = head2;//指针重新指向头
}//for
}
int main(void)
{
int arr[] = { 4,3,45,2,3,4,3,2,4,3,3,3,45,3,1};
struct node* head = list_create(arr, 15);
list_sort(head);
for (int i = 0; i < 15; ++i)
{
std::cout << head->val << std::endl;
head = head->next;
}
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
单向链表排序可以通过不同的排序算法来实现,比如冒泡排序、插入排序、选择排序、归并排序和快速排序等。下面以冒泡排序为例进行说明。 冒泡排序是一种简单的排序算法,它重复地遍历表,并通过两个相邻节点的比较来交换节点的位置,直到整个表有序为止。具体实现步骤如下: 1. 设置两个指针,一个指向表的头节点,另一个指向头节点的下一个节点。 2. 遍历表,比较当前节点和下一个节点的值,如果需要交换位置则交换。 3. 继续遍历表,直到指针指向表的尾节点。 4. 如果有任何节点交换了位置,则重新开始遍历表,直到没有节点需要交换位置为止。 5. 表排序完成。 下面是使用C语言实现的单向链表排序代码: ```c #include <stdio.h> // 定义表节点结构 struct ListNode { int val; struct ListNode *next; }; // 冒泡排序函数 void bubbleSort(struct ListNode *head) { if (head == NULL || head->next == NULL) { return; } int swapped; struct ListNode *ptr1; struct ListNode *lptr = NULL; do { swapped = 0; ptr1 = head; while (ptr1->next != lptr) { if (ptr1->val > ptr1->next->val) { // 交换节点位置 int tmp = ptr1->val; ptr1->val = ptr1->next->val; ptr1->next->val = tmp; swapped = 1; } ptr1 = ptr1->next; } lptr = ptr1; } while (swapped); } // 测试用例 int main() { // 创建表 struct ListNode n1, n2, n3, n4; n1.val = 4; n2.val = 2; n3.val = 1; n4.val = 3; n1.next = &n2; n2.next = &n3; n3.next = &n4; n4.next = NULL; // 排序表 bubbleSort(&n1); // 输出排序结果 struct ListNode *ptr = &n1; while (ptr != NULL) { printf("%d ", ptr->val); ptr = ptr->next; } return 0; } ``` 以上代码中,我们首先定义了一个表节点结构 `struct ListNode`,包含一个整数值 `val` 和一个指向下一个节点的指针 `next`。然后我们使用冒泡排序算法实现了 `bubbleSort` 函数,最后在 `main` 函数中创建了一个测试用例并进行排序输出。输出结果为 `1 2 3 4`,表示表已经按照从小到大的顺序进行了排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值