题目描述
请根据输入数据构造一个带头结点的单链表,链表结点的数据结构为struct node {int data; struct node *next;},试设计算法:按递增次序输出单链表中各结点的数据元素,并释放结点所占用的存储空间。
要求:不允许使用数组作为辅助存储空间。
输入
每组测试数据包括两行,第一行为单链表中的元素个数n;第二行为n个元素的值。
输出
排序后的元素值,每组测试数据输出占一行,行末无空格。
样例输入
6 4 5 9 3 2 1
样例输出
1 2 3 4 5 9
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
void Insert(struct node*p,int i,int a)//插入新元素(尾插)
{
while(p->next)
{
p=p->next;
}
struct node ss;
struct node *s;//每新加一个元素就要申请一块新的内存来存储新元素
s=(struct node*)malloc(sizeof(ss));//然后再把它连接到原先的链表当中
s->data=a;
s->next=NULL;
p->next=s;
}
int main()
{
int n;
scanf("%d",&n);
struct node *p;
struct node nn;
p=(struct node*)malloc(sizeof(nn));
if(p==NULL)return -1;
p->next=NULL;//初始化头指针
for(int i=0;i<n;i++)
{
int a;
scanf("%d",&a);
Insert(p,i,a);//每输入一个元素,插入一次
}
struct node*tail=p;
while(tail!=NULL)tail=tail->next;
for(int i=0;i<n;i++)//冒泡排序
{
struct node*curr=p->next;
struct node*pre=p;
for(int j=0;j<n-1;j++)
{
if(curr->data>curr->next->data)
{
struct node*q=curr->next->next;
pre->next=curr->next;
curr->next->next=curr;
curr->next=q;
if(curr->next==tail)tail=curr;//尾指针特判
}
pre=pre->next;
curr=pre->next;
}
}
p=p->next;
while(p->next)
{
printf("%d ",p->data);
p=p->next;
}
printf("%d",p->data);//这里是怕行末无空格,所以最后一个元素分开输出了
free(p);
}