My task is to write a code which builds a list of candidates entered from command line & sort them alphabetically on the fly with linked list.
The problem is if I put in the final loop
if (CandidatesList)
the program does not ever get to execute the function InsertAfter. It is InsertFirst all the way.
on the other hand if I put
if (CandidatesList->Next==NULL)
The first value in list get the InsertFirst, then all following values are in the order of input entered to the list- last on in list- first entered & not alphabetically manner.
help will be highly appreciated!Code:#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct{
char FName[15];
char LName[20];
int ID;
int LearnYrs;
int ExperienceYrs;
int TheoreticalGrd;
int PracticalGrd;
}CandidateDetails;
typedef CandidateDetails Candidate;
Candidate CurrentCandidate;
struct LinkedList{
Candidate Data;
struct LinkedList *Next;
};
typedef struct LinkedList Node;
typedef Node *PtrToNode;
PtrToNode InitList()
{
PtrToNode P;
P = (PtrToNode) malloc(sizeof(Node));
if (P == NULL)
puts ("Out of memory! 1");
P->Next = NULL;
return P;
}
int IsEmptyList(PtrToNode list)
{
return (list->Next == NULL);
}
PtrToNode getnode (void)
{
PtrToNode p;
p=(PtrToNode)malloc(sizeof (struct LinkedList));
return p;
}
void InsertFirst(PtrToNode *list, Candidate name)
{
PtrToNode TmpCell;
TmpCell=getnode();
if (TmpCell)
{
TmpCell->Data = name;
TmpCell->Next = *list;
*list = TmpCell;
}
else
{
puts ("Out of memory! 2");
}
}
void InsertAfter(PtrToNode list, Candidate name)
{
PtrToNode TmpCell;
if (list)
{
TmpCell=getnode();
if (TmpCell)
{
TmpCell->Data=name;
TmpCell->Next = list->Next;
list->Next=TmpCell;
list=TmpCell;
}
else
{
puts ("Error in InsertAfter");
}
}
else
{
puts ("Out of memory! 3");
}
}
void PrintList (PtrToNode list)
{
while (list)
{
printf ("%s %s", list->Data.FName, list->Data.LName);
list= list->Next;
}
printf ("\n");
}
int main (void)
{
int i=0;
PtrToNode CandidatesList, p, q;
CandidatesList=InitList();
CurrentCandidate.ID=1;
while (CurrentCandidate.ID !=0)
{
puts ("\nAll of the following details has to be of the same candidate");
puts ("\nPlease enter an ID number of one of the candidate");
flushall();
scanf ("%d", &CurrentCandidate.ID);
if (CurrentCandidate.ID==0)
break;
puts ("\nPlease enter the first name of the candidate");
flushall();
fgets (CurrentCandidate.FName, 15, stdin);
puts ("\nPlease enter the last name of the candidate");
flushall();
fgets (CurrentCandidate.LName, 20, stdin);
if (IsEmptyList (CandidatesList))
InsertFirst(&CandidatesList, CurrentCandidate);
else
{
p=CandidatesList;
while (p && strcmp(p->Data.LName,
CurrentCandidate.LName)<0)
{
q=p;
p=p->Next;
}
InsertAfter(CandidatesList, CurrentCandidate);
}
PrintList (CandidatesList);
}
}
TIA.