问题:用单链表按照学号从小到大的顺序记录某高校每个学生在校期间所获得学分的总和,每个学生的学号唯一。
#include <stdio.h>
#include <stdbool.h>
typedef struct Node_t
{
int id;
int score;
struct Node_t *next;
}Node;
Node node;
static int count=0;
/*insert node and sort,id is unique
1、通过判断count的值,若是第一个节点,直接进行赋值
2、首先判断该id是否已添加,若添加,进行score的取和,并进行排序
3、若没有相同的id,添加节点并进行排序存放
*/
int insert(int id,int score)
{
Node *q=NULL;
Node *r=NULL;
bool flag=false;
int tempscore=0;
int tempid=0;
q=&node;
if(0 == count)
{
q->id=id;
q->score=score;
count+=1;
return 0;
}
while(q)
{
/*same id then sum of score*/
if(q->id== id)
{
q->score+=score;
while(q)
{
if(q->next != NULL)
{
/*to sort*/
if(q->score > q->next->score)
{
printf("score1=%d,score2=%d\n",q->score,q->next->score);
tempid=q->id;
tempscore=q->score;
q->id=q->next->id;
q->score=q->next->score;
q->next->id=tempid;
q->next->score=tempscore;
}
}
q=q->next;
}
flag=true;
break;
}
q=q->next;
}
if(false == flag)
{
r=malloc(sizeof(Node));
r->id=id;
r->score=score;
count+=1;
q=&node;
while(q)
{
if(q->next == NULL)
{
q->next=r;
break;
}
if(q->score >= score)
{
r->next=q->next;
q->next=r;
r->id=q->id;
r->score=q->score;
q->id=id;
q->score=score;
flag=true;
break;
}
q=q->next;
}
}
}
int main()
{
int a[5][5]={{2,3},{3,2},{5,6},{4,7},{5,2}};
int i=0;
int j=0;
Node *p=NULL;
for(i=0;i<5;i++)
{
insert(a[i][0],a[i][1]);
}
p=&node;
while(p)
{
printf("%d/%d ",p->id,p->score);
p=p->next;
}
return 0;
}