C语言单向链表的一个简单问题
求热心牛人帮帮忙。。
看一下以下这段代码,要求是建立一个动态链表,输入第一个学号和成绩的时候就创建第一个节点,然后接着输入学号和成绩,输入0,0则退出,然后打印出学号和成绩。
代码如下:
#include<stdio.h>
#include<stdlib.h>
struct student
{
int number;
float score;
struct student *next;
};
int main()
{
int n=0;
struct student *head,*p1,*p2;
p1=(struct student*)malloc(sizeof(struct student));
p2=(struct student*)malloc(sizeof(struct student));
scanf("%d %f",&p1->number,&p1->score); //输入学生学号,成绩
head=NULL;
while(p1->number!=0 && p1->score!=0) //如果输入 0,0 则退出
{
n=n+1;
if(n==1) head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student*)malloc(sizeof(struct student));
scanf("%d %f",&p1->number,&p1->score);
}
p2->next=NULL;
struct student *p3,*p4;
p3=(struct student*)malloc(sizeof(struct student));
p4=(struct student*)malloc(sizeof(struct student));
for(int i=0;i<n;i++) //以下将学生的学号按从小到大的顺序排序,为什么结果显示不出来呢?哪里错了?
{
p3=head;
for(int j=i+1;j<n;j++)
{
p4=p3->next;
if(p3->number>p4->number)
{
int k=p3->number;
p3->number=p4->number;
p3->number=k;
}
p3=p3->next;
}
}
do
{
printf("%d %.0f\n",head->number,head->score); //打印学号和成绩
head=head->next;
}while(head!=NULL);
return 0;
}
主要问题是现在学号和成绩输出的时候不是按照学号从小到大的顺序输出的,求大牛帮忙!无比感谢加送分!
[解决办法]
修改完成了,VS2008测试通过。排序使用的是冒泡。最好就是链表没有释放,留给你自己解决了。给分吧!
#include<stdio.h>#include<stdlib.h>struct student{ int number; float score; struct student *next;};int main(){ int n=0; struct student *head,*p1,*p2; p1=(struct student*)malloc(sizeof(struct student));// p2=(struct student*)malloc(sizeof(struct student));//好像多余了吧。因为这个节点没有用过 scanf("%d %f",&p1->number,&p1->score); //输入学生学号,成绩 head=NULL; while(p1->number!=0 && p1->score!=0) //如果输入 0,0 则退出 { n=n+1; if(n==1) head=p1; else p2->next=p1; p2=p1; p1=(struct student*)malloc(sizeof(struct student)); scanf("%d %f",&p1->number,&p1->score); } p2->next=NULL; struct student *p3,*p4;// p3=(struct student*)malloc(sizeof(struct student));// p4=(struct student*)malloc(sizeof(struct student)); for(int i=0;i<n;i++) //以下将学号按从小到大的顺序排序,为什么结果显示不出来呢?哪里错了? { p3=head; for(int j=0;j<n-i-1;j++) { p4=p3->next; if(p3->number>p4->number) { int k=p3->number; p3->number=p4->number; p4->number=k; } p3=p3->next; } } p3 = head; do { printf("%d %.0f\n",p3->number,p3->score); //打印学号和成绩 p3=p3->next; }while(p3!=NULL); return 0;}