Everyone! I was given list of data with countries and number of enrollees male and female in the table, my task is to read in and sort the sum in descending order.
Have no problems with reading in, but I have problems with sorting as you may guess.
On the output I have only 2 countries instead of 158.
Here is my code
#include<stdlib.h>
#include<stdio.h>
typedef struct _person_count {
char country[80];
long females;
long males;
struct _person_count *link;
} person_count;
void printList(person_count *node) {
if (node != NULL) {
printf("%25s %10d %10d %10d \n", node->country, node->females,
node->males, node->males + node->females);
printList(node->link);
}
}
int main() {
FILE *infile;
infile = fopen("file.txt", "r");
if (infile == NULL) {
printf("Problem opening files.");
return 1;
}
person_count *first = NULL;
person_count *curr = NULL;
person_count *prev = NULL;
person_count *a = NULL;
do {
person_count *newNode = malloc(sizeof(person_count));
fscanf(infile, "%s %ld %ld", &newNode->country, &newNode->females,
&newNode->males);
newNode->link = NULL;
if (first == NULL) {
first = newNode;
} else {
prev->link = newNode;
};
curr = first;
if ((newNode->females + newNode->males)
> (first->females + first->males)) {
newNode->link = first;
first = newNode;
} else {
do {
if (curr->link == NULL) {
curr->link = newNode;
printf("a\n");
break;
}
if ((newNode->females + newNode->males)
< (curr->link->females + curr->link->males)) {
curr = curr->link;
printf("b\n");
continue;
} else {
newNode->link = curr->link;
curr->link = newNode;
printf("c\n");
break;
}
} while (curr->link->link != NULL);
}
prev = newNode;
} while (!feof(infile));
printList(first);
printf("\n\n\nnew\n\n\n");
printList(curr);
return 0;
}
It return this output
China 47803801 52828124 100631925
India 38383177 51078616 89461793
USA 12008749 12423185 24431934
Vietnam 4827551 5111768 9939319
Yemen 466693 988523 1455216
Zambia 183200 225771 408971
new
Yemen 466693 988523 1455216
Zambia 183200 225771 408971
Could you help?
Thank you in advance!