Posted on 2012-08-12 22:23
hoshelly 閱讀(2018)
評論(0) 編輯 收藏 引用 所屬分類:
Programming 、
DS && Algorithm
輸入10個學生的成績,編寫一程序對學生的成績按從高到低輸出,要求用鏈表實現。
#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));
//創建頭結點
if(head == NULL)
{
printf("Memory is not enough!");
return 0;
}
head->next=NULL;
for(i=0;i<10;i++)
{
p=(Node*)malloc(
sizeof(Node));
//創建一個新結點p
if(p == NULL)
{
printf("no enough memory!");
return 0;
}
printf("Input the %dth student's score: ",i+1);
scanf("%d",&p->score);
//輸入成績
q=head;
while(q->next != NULL)
//遍歷鏈表
{
if(q->next->score < p->score)
//如果發現鏈表中的某個成績比當前輸入成績小,就跳出循環,在其前面插入當前輸入成績
break;
q=q->next;
//繼續遍歷直到遍歷的成績比當前輸入的成績小
}
p->next=q->next;
//這是當前成績插入到鏈表中比其小的成績前面的代碼
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);
return 0;
}