I'm trying to get this program to print out the employee with the highest ID number. But instead, it prints out all of the employees, with the last name is in the first name position, and the last name position never gets filled. I've been working on this for a while now. I'm new to programming and i am having a hard time with linked lists. Any help would be appreciated.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NO_APPTS 4
typedef struct work
{char first_name[21];
char last_name[21];
int id;
struct work *next;
}APPT;
APPT* insertit(APPT*first, char first_name[], char last_name[], int id);
int main(void)
{
APPT *head,
*p;
char fname[21];
char lname[21];
int ident,
j,
k;
char ch,
nl;
head=NULL;
for(j=0;j<21;j++)
{fname[j]=' ';
lname[j]=' ';
}
for(k=0;k<NO_APPTS;k++)
{printf("Enter the first name of the employee\n");
printf("is to be made...max 20 characters :");
gets(fname);
printf("Enter the last name of the employee ");
printf("is to be made...max 20 characters :");
gets(lname);
printf("Enter the 3 digit employee id number: ");
scanf("%d", &ident);
scanf("%c", &nl);
head=insertit (head,fname,lname,ident);
for (j=0;j<21;j++)
{fname[j]=' ';
lname[j]= ' ';}
}
p=head;
while (p!=NULL)
{printf("The first name of the employee is: %s ", p->first_name);
printf("The last name of the employee is: %s ", p->last_name);
printf("The 3 digit id number of the empoyee is: %d\n",p->id);
p=p->next;
}
printf("Hit any character to continue");
scanf("%c",&ch);
}
APPT* insertit (APPT *first, char first_name[], char last_name[], int ident)
{ APPT *p,
*q,
*newp;
int found,
len,
i;
found=0;
q=first;
p=first;
while ((p!=NULL) && (!found))
{ if (p->id < ident)
{
q=p;
p=p->next;
}
else
found=1;
}
newp=(APPT*) malloc(sizeof(APPT));
newp->id=ident;
strncpy(newp->first_name, last_name, 21);
newp->next=p;
if(q!=p)
q->next=newp;
else
first=newp;
return(first);
}