I'm trying to create a sorted list in ascending order. I must read a file which contains a year in every line ( so I want to order from the earliest date to the most recent).
What I'm trying to accomplish with my code is:
- List item
- Retrieve data (year) from a line of the .csv file;
- Iterate over the list until the place for the node containing data is found;
- Repeat until the file is over;
- Print;
Whenever I try to run it, the Virtual box starts lagging and doesn't do anything. (even when I remove the print function).
I've been trying to solve this for 3 days now, so I'm quite desperate.
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
} node;
struct node *head_countries = NULL;
struct node *current = NULL;
//display the list
void printList() {
struct node *ptr = head_countries;
printf("\n[ ");
//start from the beginning
while(ptr != NULL) {
printf("(%d,%d)",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
//insert link at the first location
struct node* insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
//point it to old first node
link->next = head_countries;
//point first to new first node
head_countries = link;
return link;
}
void insertAfter(struct node* PrevNode, int key, int data)
{
struct node *NewNode = (struct node*) malloc(sizeof(struct node));
if ( PrevNode == NULL )
{
printf("Erro 1");
return;
}
NewNode->key = key;
NewNode->data = data;
NewNode->next = PrevNode->next;
PrevNode->next = NewNode;
}
void CreateCountriesList()
{
char linha[150];
char cabecalho[100];
int key = 0, data = 0;
int test[15] = {0};
test[0] = 10;
test[1] = 25;
test[2] = 7;
test[3] = 5;
test[4] = 30;
test[5] = 40;
test[6] = 3;
test[7] = 4;
test[8] = 98;
test[10] = 4;
test[11] = 14;
test[12] = 23;
test[13] = 16;
test[14] = 35;
test[15] = 6;
//dados_temp New_Entry;
struct node* curr_head = NULL;
struct node* curr = NULL;
FILE *inputf;
inputf = fopen("tempcountries_all.csv", "r");
if (inputf == NULL)
{
printf("Nao da pa abrir o ficheiro");
exit(EXIT_FAILURE);
}
fgets(cabecalho, 100, inputf);
for (key = 0; key < 20 ; key++)
{
data = test[key]
if ( head_countries == NULL || key == 2 )
{
insertFirst( key, data );
}
else
{
curr = head_countries;
//insertAfter(curr, key, data);
//printf("%d\n", curr->data);
//curr = curr->next;
while ( curr->next != NULL )
{
//printf("%d", key);
if ( curr->data < data && curr->next->data > data )
{
insertAfter(curr, key, data);
}
if ( data == curr->data )
{
//insertAfter(curr, key, data);
}
curr = curr->next;
}
}
}
printList();
fclose(inputf);
}
int main() {
CreateCountriesList();
return EXIT_SUCCESS;
}
Is it because the list is too big? If so, how do you recommend I proceed for a list this big?
Thank you in advance!
EDIT: removed warnings from code, and unused functions.
EDIT: added test.