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;
}