用鏈表實(shí)現(xiàn)學(xué)生成績(jī)的排序
Posted on 2012-08-12 22:23 hoshelly 閱讀(2038) 評(píng)論(0) 編輯 收藏 引用 所屬分類: Programming 、DS && Algorithm輸入10個(gè)學(xué)生的成績(jī),編寫一程序?qū)W(xué)生的成績(jī)按從高到低輸出,要求用鏈表實(shí)現(xiàn)。
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
int score;
struct Stu *next;
};
typedef struct Stu Node;
int main()
{
int i;
Node *head,*p,*q;
head=(Node*)malloc(sizeof(Node)); //創(chuàng)建頭結(jié)點(diǎn)
if(head == NULL)
{
printf("Memory is not enough!");
return 0;
}
head->next=NULL;
for(i=0;i<10;i++)
{
p=(Node*)malloc(sizeof(Node)); //創(chuàng)建一個(gè)新結(jié)點(diǎn)p
if(p == NULL)
{
printf("no enough memory!");
return 0;
}
printf("Input the %dth student's score: ",i+1);
scanf("%d",&p->score); //輸入成績(jī)
q=head;
while(q->next != NULL) //遍歷鏈表
{
if(q->next->score < p->score) //如果發(fā)現(xiàn)鏈表中的某個(gè)成績(jī)比當(dāng)前輸入成績(jī)小,就跳出循環(huán),在其前面插入當(dāng)前輸入成績(jī)
break;
q=q->next; //繼續(xù)遍歷直到遍歷的成績(jī)比當(dāng)前輸入的成績(jī)小
}
p->next=q->next; //這是當(dāng)前成績(jī)插入到鏈表中比其小的成績(jī)前面的代碼
q->next=p;
}
p=head->next;
while(p !=NULL)
{
printf("%d ",p->score);
p=p->next;
}
return 0;
}
#include<stdlib.h>
struct Stu
{
int score;
struct Stu *next;
};
typedef struct Stu Node;
int main()
{
int i;
Node *head,*p,*q;
head=(Node*)malloc(sizeof(Node)); //創(chuàng)建頭結(jié)點(diǎn)
if(head == NULL)
{
printf("Memory is not enough!");
return 0;
}
head->next=NULL;
for(i=0;i<10;i++)
{
p=(Node*)malloc(sizeof(Node)); //創(chuàng)建一個(gè)新結(jié)點(diǎn)p
if(p == NULL)
{
printf("no enough memory!");
return 0;
}
printf("Input the %dth student's score: ",i+1);
scanf("%d",&p->score); //輸入成績(jī)
q=head;
while(q->next != NULL) //遍歷鏈表
{
if(q->next->score < p->score) //如果發(fā)現(xiàn)鏈表中的某個(gè)成績(jī)比當(dāng)前輸入成績(jī)小,就跳出循環(huán),在其前面插入當(dāng)前輸入成績(jī)
break;
q=q->next; //繼續(xù)遍歷直到遍歷的成績(jī)比當(dāng)前輸入的成績(jī)小
}
p->next=q->next; //這是當(dāng)前成績(jī)插入到鏈表中比其小的成績(jī)前面的代碼
q->next=p;
}
p=head->next;
while(p !=NULL)
{
printf("%d ",p->score);
p=p->next;
}
p=head;
while(p->next !=NULL)
{
q=p->next;
p->next=q->next;
free(q);
}
free(head);
while(p->next !=NULL)
{
q=p->next;
p->next=q->next;
free(q);
}
free(head);
return 0;
}