C++日常练习(4)

18、实现一个对单链表进行冒泡排序的函数,以链表的头节点指针作为函数参数传递(头节点不存储数据)。


#define _CRT_SECURE_NO_WARNINGS
#include"stdio.h"
#include"stdlib.h"
typedef struct Linked
{
	int num;
	struct Linked *next;
}S;
typedef struct L
{
	S *head;
	S *end;
	int x;
	int lenght;
}LL;
LL *arr_init()
{
	LL *s;
	
	s = (LL*)malloc(sizeof(LL));
	if (NULL == s)
	{
		printf("空间开辟失败!\n");
		return NULL;
	}
	s->head = NULL;
	s->end = NULL;
	s->lenght = 0;
	return s;
}
S *arr_init2(int num)
{
	S *temp = (S *)malloc(sizeof(S));
	if (NULL == temp)
	{
		printf("空间开辟失败!\n");
		return NULL;
	}
	temp->num = num;
	temp->next = NULL;
	return temp;
}
void arr_sort(LL *s, int num)
{
	if (NULL == s)
	{
		printf("链表不存在!\n");
	}
	if (s->head == NULL)
	{
		s->head = s->end = arr_init2(num);
		s->lenght++;
	}
	else
	{
		s->end = s->end->next = arr_init2(num);
		s->lenght++;
	}
}
void arr_print(LL *s)
{
	if (NULL == s || NULL == s->head)
	{
		printf("链表为空,输出失败!\n");
		return;
	}
	for (S *temp = s->head; temp != NULL; temp = temp->next)
	{
		printf("%d->", temp->num);
	}
	puts("NULL\n");
}
void arr_maopao(LL *s, int num)
{
	do {
		S *temp = s->head;
		num = num - 1;
		for (temp = s->head, s->x = 0; s->x < num; temp = temp->next, s->x++)
		{
			if (temp->num > temp->next->num)
			{
				temp->num = temp->num + temp->next->num;
				temp->next->num = temp->num - temp->next->num;
				temp->num = temp->num - temp->next->num;
			}
		}
	} while (num != 2);
}
int main(void)
{
	LL *q = arr_init();
	int number;
	printf("输入数据:");
	do
	{
		scanf("%d", &number);
		arr_sort(q, number);
	} while ('\n' != getchar());
	arr_maopao(q, q->lenght);
	printf("数据为:\n");
	arr_print(q);
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秘密之乡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值