天之道

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

创建动态链表

Posted on 2012-05-12 10:29 hoshelly 阅读(1791) 评论(0)  编辑 收藏 引用 所属分类: DS && Algorithm

建立一个链表,其中的节点包括学号,成绩信息。要求用动态插入链表的方法实现,就是输入第一个节点信息时,则必须创建该链表,之后每输入一个学生节点的基本信息,就把该节点插入到已有的链表当中。要求按照学号顺序插入。输入的时候可以不按照学号的顺序,输入0 0 表
示输入结束。
(不允许对输入的数据排序后再创建链表)

Sample Input

1 50
4 60
2 70
3 80
5 64
0 0 

Sample Output

The list is:
1 50
2 70
3 80
4 60
5 64



#include<stdio.h>
#include<stdlib.h>

struct student
{
    int number;
    float score;
    struct student *next;
};

int main()
{
    int n=0;
    struct student *head,*p1;
    p1=(struct student*)malloc(sizeof(struct student));
    scanf("%d %f",&p1->number,&p1->score);
    head=p1;
    head->next=NULL;
    while(p1->number!=0 && p1->score!=0)
    {
          n++;
          p1->next=(struct student*)malloc(sizeof(struct student));
          p1=p1->next;
          p1->next=NULL;
          scanf("%d %f",&p1->number,&p1->score);
    }
    
    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;
                float m=p3->score;
                p3->score=p4->score;
                p4->score=m;
            }
            p3=p3->next;
        }
    }
    printf("The list is:\n");
     p3=head;
     do
     {
      if(p3->number ==0 && p3->score==0)
          continue;
      printf("%d %.0f\n",p3->number,p3->score); 
      p3=p3->next;
    }while(p3!=NULL);

    free(p1);
    free(p3);
    free(p4);
    return 0;
}
    

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