题目描述
问题描述:已知一个正整数组成的无序序列,个数未知,但至少有一个元素,你的任务是建立一个单链表,并使用该链表存储这个正整数序列,然后将这个链表进行排序,使得排序后的链表为递增序列。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。在排序的过程中,你可以自己选择排序算法(冒泡排序、选择排序等),但必须是通过修改结点的指针域来进行排序,而不是对结点的数据域进行修改。程序结束后要释放所有节点占据的空间。
输入与输出要求:输入一个元素个数未知的正整数序列,以输入“-1”结束,输入“-1”前至少输入一个正整数。输出经过排序后的链表,每个元素后有一个空格,注意最后一个元素后只有换行符。
数据最多的测试用例节点数在1000这个数量级,所有整数可以用int型存储。
请注意输入输出格式。
输入样例
49 38 65 97 76 13 27 49 -1
输出样例
The new list is:13 27 38 49 49 65 76 97
#include<stdio.h>
#include<stdlib.h>
struct node//链表结构
{
int data;
struct node *next;
};
typedef struct node NODE;//重命名
NODE * createNode();//创建链表函数
void freeList(NODE * head);//释放链表函数
void bubbleSort(NODE * head);//冒泡排序
int cnt;//记录元素个数
int main()
{
NODE *head=createNode();
NODE *temp = head;//用于最后的释放
printf("The new list is:");
if (cnt == 1)
printf("%d\n", head->next->data);
else
{
bubbleSort(head);
head = head->next;
while (head->next != NULL)//打印
{
printf("%d ", head->data);
head = head->next;
if (head->next == NULL)
{
printf("%d\n", head->data);
break;
}
}
}
freeList(temp);//释放
temp = NULL;
return 0;
}
NODE * createNode()//创建一个含有头节点的链表
{
int num;
NODE * current = NULL;
NODE * last = NULL;
NODE * head = NULL;
head = malloc(sizeof(NODE));
head->data = 0;
head->next = NULL;
last = head;
scanf("%d", &num);
while (num != -1)
{
cnt++;
current = malloc(sizeof(NODE));
if (current != NULL)
{
current->data = num;
last->next = current;
current->next = NULL;
last = current;
}
scanf("%d", &num);
}
last->next = NULL;
return head;
}
void freeList(NODE * head)
{
NODE * temp;
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
}
void bubbleSort(NODE * head)//冒泡排序,适用于有头节点的链表,否则第一个元素将无法参与排序
{
NODE * pre,* p,* tail;
tail = NULL;
while (head->next != tail)
{
pre = head;
p = head->next;
while (p->next != tail)
{
if (p->data > p->next->data)
{
pre->next = p->next;
p->next = pre->next->next;
pre->next->next = p;
}
else
p = p->next;
pre = pre->next;
}
tail = p;
}
}