Link lit in c is a challenging lesson but I am grateful that I learned it.
it was such a practical lesson. Though I still prefer to program arrays, I still find dynamic memory allocation handy. I have learned techniques that are handy.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_C 200
typedef char string7[8];
typedef char string25[26];
typedef struct
{
string25 first, last;
char mid;
}nameType;
struct courseTag
{
string7 courseCode;
float units, grade;
nameType facultyName;
};
typedef struct courseTag arrCourses[MAX_C];
struct studentTag
{
nameType name;
arrCourses course;
int numCourse;
float CGPA;
struct studentTag *pLink;
};
typedef struct studentTag *ptrStudent; /*this alias can be used to avoid confusion in using an asterisk*/
/*you can not use the same typedef call like nameType in studentTag, because you will be calling the alias that hasn't been declared yet*/
/*This function allows to insert node in alphabetical order*/
void insert(ptrStudent *pFirst){/*Alphabtical insertion*/
char tmp;
ptrStudent pNew,pRun,pLast;
pNew=malloc(sizeof(struct studentTag));
printf("Enter first name: ");
fgets(pNew->name.first,sizeof(string25),stdin);
printf("Enter miidle intial: ");
scanf("%c%c",&pNew->name.mid,&tmp);
printf("Enter last name: ");
fgets(pNew->name.last,sizeof(string25),stdin);
pNew->pLink=NULL;
if(*pFirst==NULL)
*pFirst=pNew;
else
if(strcmp((*pFirst)->name.last,pNew->name.last)>0)
{
pNew->pLink=*pFirst;
*pFirst=pNew;
}
else {
pRun=*pFirst;
while(pRun!=NULL&&strcmp(pRun->name.last,pNew->name.last)<0)
{
pLast=pRun;
pRun=pRun->pLink;
}
if(pRun)
pNew->pLink=pRun;
pLast->pLink=pNew;
}
}
No comments:
Post a Comment