C语言链表之冒泡排序!!!

2024-11-23 07:53:03
推荐回答(4个)
回答1:

主要是循环次数上有问题,修改的地方都做了标记:
#include
#include
//#define null 0 ---把数等于零写成NULL不是好习惯,NULL一般是用来说指针为0,这个在标准库中有定义

struct number
{
int num;
struct number *next;
};

void main()
{
struct number *head;
struct number *p1,*p2,*p;
int n=0,m,i,j;
p1=(struct number *)malloc(sizeof(struct number)); //这里的p2没用上,删掉
printf("\nWang jianfei 060806110006\n\n\n");
printf("Please enter the number: ");
scanf("%d",&p1->num);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(head==NULL) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct number *)malloc(sizeof(struct number));
scanf("%d",&p1->num);
}
p2->next=NULL;
p=head;
//m=head->num; 这句没有用,删掉
for(i=1;i {
for(j=0;j {
if(p->next->num > p->num)
{
m=p->next->num;
p->next->num=p->num;
p->num=m;
p=p->next;
}
}
p=head;
}
printf("\nNow,there %d numbers are: ",n);
p=head;
while(p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}
}

回答2:

#include
#include

struct number
{
int num;
struct number *next;
};

void main()
{
struct number *head;
struct number *p1,*p2,*p,*p3,*p4;
int n=0,m,i,j;
p1=p2=(struct number *)malloc(sizeof(struct number));
printf("\nWang jianfei 060806110006\n\n\n");
printf("Please enter the number: \n");
scanf("%d",&p1->num);
head=NULL;
while(p1->num!=NULL)
{
n=n+1;
if(head==NULL) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct number *)malloc(sizeof(struct number));
scanf("%d",&p1->num);
}
p2->next=NULL;
p=head;

for(p4=head;p4!=NULL;p4=p4->next)
{
for(p3=head;p3->next!=NULL;p3=p3->next)
{

if(p4->num>p3->num)
{

m=p4->num;
p4->num=p3->num;
p3->num=m;

}

}
p=head;
}
printf("\nNow,there %d numbers are: ",n);
p=head;
printf("\n");
if(head!=NULL)
do
{
printf("%5d ",p->num);
p=p->next;
}while(p!=NULL);
printf("\n");
getch();
}

回答3:

将用于排序的内循环改成for(j=i;j

回答4:

for(i=0;i{
for(j=0;j//应该是j=1吧,你试试
p1=p2=(struct number *)malloc(sizeof(struct number));
//这句改为p1=(struct number *)malloc(sizeof(struct number));
改动这两处,OK!