連結串列排序(氣泡排序)
阿新 • • 發佈:2019-02-07
typedef struct StudentType
{
int a;
struct StudentType *next;
} *Linklist,Link;
Linklist Build(int n)
{
Linklist p=NULL,s=NULL,ptr=NULL;
int i;
p=(Linklist)malloc(sizeof(Link));
p->next=NULL;
ptr=p;
for(i=0;i<n;i++)
{
s=(Linklist)malloc(sizeof(Link));
scanf("%d",&s->a);
ptr->next=s;
ptr=s;
}
ptr->next=NULL;
return p;
}
void Print(Linklist ptr)
{
Linklist p=ptr->next;
while(p)
{
printf("%d\n",p->a);
p=p->next;
}
}
void Paixu(Linklist ptr)
{
Linklist p=ptr->next,s=NULL;
int temp,i=ptr->a-1;
while(i>=0)
{
p=ptr->next;
while(p->next)
{
if(p->a>p->next->a)
{
temp=p->a;
p->a=p->next->a;
p->next->a=temp;
}
p=p->next;
}
i--;
}
}
int main()
{
int n;
Linklist head=NULL;
scanf("%d",&n);
head=Build(n);
head->a=n;
Paixu(head);
Print(head);
return 0;
}
{
int a;
struct StudentType *next;
} *Linklist,Link;
Linklist Build(int n)
{
Linklist p=NULL,s=NULL,ptr=NULL;
int i;
p=(Linklist)malloc(sizeof(Link));
p->next=NULL;
ptr=p;
for(i=0;i<n;i++)
{
s=(Linklist)malloc(sizeof(Link));
scanf("%d",&s->a);
ptr->next=s;
ptr=s;
}
ptr->next=NULL;
return p;
}
void Print(Linklist ptr)
{
Linklist p=ptr->next;
while(p)
{
printf("%d\n",p->a);
p=p->next;
}
}
void Paixu(Linklist ptr)
{
Linklist p=ptr->next,s=NULL;
int temp,i=ptr->a-1;
while(i>=0)
{
p=ptr->next;
while(p->next)
{
if(p->a>p->next->a)
{
temp=p->a;
p->a=p->next->a;
p->next->a=temp;
}
p=p->next;
}
i--;
}
}
int main()
{
int n;
Linklist head=NULL;
scanf("%d",&n);
head=Build(n);
head->a=n;
Paixu(head);
Print(head);
return 0;
}