天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

用链表实现学生成绩的排序

Posted on 2012-08-12 22:23 hoshelly 阅读(1973) 评论(0)  编辑 收藏 引用 所属分类: ProgrammingDS && 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;
}


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理