the program should do the insertion ascending sort for the nodes,first it should check the names and if the names are equal it should sort the ids,i do not know what is the issue that does not sort properly.
# 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);
}
An example of the contents of student.txt:
121513 ala 45.00
121510 wang 21.00
145852 frank 26.00
151515 ala 25.00
Your sorting issue is one of operator precedence
<and>have a higher precedence than=, meaning it will be evaluated first, then an assignment will take place.So your string compares in these two places:
are wrong.
scis getting the value ofstrcmp((*head)->name,p->name)> 0andstrcmp(q->name,p->name)<0respectively (note this is going to always be1or0, never-1)If you simply adjust your code as such:
You’ll see it working. Moral of the story: don’t try to be stingy with your parens or brackets, it doesn’t cost you anything to put more in, it makes the code clearer, and it saves you debugging headaches like this one.