I have created a linked list in C but it is printing in the reverse order. When printing the linked list, I want my print function to be separate from the main function. How do I print the linked list in the same order as the data was inputted?
struct CTAStations
{
int stationID;
char *stationName;
float latitude;
struct CTAStations *next;
}*head;
typedef struct CTAStations cta;
void display();
int main(int argc, const char * argv[])
{
FILE *file;
file = fopen("station8.csv","r");
char buffer[64];
if(file != NULL) {
while (!feof(file)) {
cta *node = malloc(sizeof(cta));
fgets(buffer, 64, file);
node->stationID = atoi(strtok(buffer, ","));
node->stationName = strdup(strtok(NULL, ","));
node->latitude = atoi(strtok(NULL, ","));
node->next = head;
head = node;
printf("While Loop print test: %s\n", node->stationName);
}
}
printf("\n");
display();
fclose(file);
return 0;
}
void display()
{
struct CTAStations *temp;
temp = head;
while(temp!=NULL) {
printf("%s\n",temp->stationName);
temp = temp->next;
}
}
Here is the input file:
40302,20th,39.483921
40830,18th (Pink Line),41.857908
40120,35th/Archer (Orange Line),41.829353
41120,35th-Bronzeville-IIT (Green Line),41.831677
Here is the output: enter image description here