程序应该对节点进行插入升序排序,首先它应该检查名称,如果名称相等,它应该对 id 进行排序,我不知道是什么问题没有正确排序。
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
typedef struct nd{
int id;
char name[20];
float gpa;
struct nd *next;
}node;
typedef node *list;
//---------------------------------------------------------------
int insertlist(list *head,char *buffer)
{
list p,q,n;
int m,num,k,sc;
p=(list)malloc(sizeof(node));
num=sscanf(buffer,"%d %s %f",&(p->id),(p->name),(&p->gpa));
if(num!=3)
{
printf("info not complete\n");
free(p);
return 1;
}
else
{
if(!*head)
{
*head=p;
p->next = NULL;
}
//******** sorting tthe names and ids for equal names
else if(sc=strcmp((*head)->name,p->name)> 0 || ((sc == 0) && ((*head)->id > p->id)))
{//head is modified
p->next=*head;
*head=p;
}
else{
n=*head;
q=n->next;
while(q && ((sc=strcmp(q->name,p->name)<0) || ((sc == 0) && (q->id < p->id))))
{
n=q;
q=q->next;
}
n->next=p;
p->next=q;
}
}
return 0;
}
//------------------------------------------------------
int main()
{
int id,r;
list head,p;
FILE *fp;
char c,buffer[100],filename[10];
if ((fp=fopen("student.txt","r"))==NULL)
{
printf("error opening %s",filename);
exit(1);
}
else
{
head=NULL;
while(fgets(buffer,100,fp)!=NULL)
{
buffer[strlen(buffer)-1]=='\0';
r=insertlist(&head,buffer);
}
fclose(fp);
}
for(p=head;p!=NULL;p=p->next)
printf("%d %s %f\n\n",p->id,p->name,p->gpa);
}
内容示例student.txt
:
121513 ala 45.00
121510 wang 21.00
145852 frank 26.00
151515 ala 25.00