SortByNum and SortByName functions are working but the inserting is not.
Is there other ways to do it and why it is not working can someone explain it?
Here is the onlineGDB session!
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct studInfo {
int studNr;
char studName[12];
int grade;
};
struct node {
struct studInfo info;
struct node *link;
};
typedef struct node *NODEPTR;
NODEPTR getnode(void);
void fileIntoArray(struct studInfo allStudent[], int *num);
void sortByNum(struct studInfo allstudent[], NODEPTR *, int num);
void sortByName(struct studInfo allstudent[], NODEPTR *, int num);
void insert(NODEPTR *, NODEPTR *, NODEPTR);
void list(NODEPTR);
int main() {
struct studInfo allStudent[150];
NODEPTR headNum, headName, m;
int choice;
int num;
fileIntoArray(allStudent, &num);
sortByNum(allStudent, &headNum, num);
// sortByName(allStudent, &headName, num);
// list(headName);
m = getnode();
printf("Enter a sudent infomation STUDENT Num, Name, Grade");
scanf("%d", &m->info.studNr);
scanf("%s", m->info.studName);
scanf("%d", &m->info.grade);
insert(&headNum, &headName, m);
list(headNum);
return 0;
}
void fileIntoArray(struct studInfo allStudent[], int *num) {
FILE *ptr = fopen("student.txt", "r");
int i = 0;
while (!feof(ptr)) {
fscanf(ptr, "%d%s%d", &allStudent[i].studNr,
allStudent[i].studName, &allStudent[i].grade);
i++;
}
*num = i;
fclose(ptr);
}
void sortByNum(struct studInfo allStudent[], NODEPTR *headNum, int num) {
NODEPTR head, p, prev;
head = NULL;
p = NULL;
prev = NULL;
for (int i = 0; i < num; i++) {
p = getnode();
p->info = allStudent[i];
if (head == NULL || p->info.studNr < head->info.studNr) {
p->link = head;
head = p;
} else {
prev = head;
while (prev->link && prev->link->info.studNr < p->info.studNr) {
prev = prev->link;
}
p->link = prev->link;
prev->link = p;
}
}
*headNum = head;
}
void sortByName(struct studInfo allStudent[], NODEPTR *headName, int num) {
NODEPTR head,p,prev;
head = NULL;
for (int i = 0; i < num; ++i) {
p = getnode();
p->info = allStudent[i];
if (head == NULL || strcmp(p->info.studName, head->info.studName) < 0) {
p->link = head;
head = p;
} else {
prev = head;
while (prev->link && strcmp(prev->link->info.studName, p->info.studName) < 0) {
prev = prev->link;
}
p->link = prev->link;
prev->link = p;
}
}
*headName = head;
}
void insert(NODEPTR *headNum, NODEPTR *headName, NODEPTR p) {
NODEPTR head;
int key = p->info.studNr;
while ((*headNum)->link != NULL && (*headNum)->link->info.studNr < key) {
p->link = (*headNum)->link;
(*headNum)->link = p;
}
}
void list(NODEPTR p) {
int line = 0, c;
while (p != NULL) {
line++;
if (line > 25) {
printf("Press enter>");
fflush(stdout);
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("\r \r");
line = 1;
}
printf("%d %d %s %d\n", line, p->info.studNr,
p->info.studName, p->info.grade);
p = p->link;
}
}
NODEPTR getnode(void) {
NODEPTR q;
q = (NODEPTR)malloc(sizeof(struct node));
return (q);
}