单向链表的冒泡排序

这篇博客介绍了如何使用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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值