Вид вставки связанного списка со структурой в c - PullRequest
0 голосов
/ 19 января 2020

Я новичок здесь и в программировании в целом (обратите внимание, администраторы и гуру программирования на go легко для меня, спасибо), и я делаю домашнее задание для школы в c о маленькой программе, которая читает CSV-файл в односвязный список, в котором данные представляют собой структуру, затем сортирует их и отображает.

CSV-файл содержит информацию о сотруднике, такую ​​как его имя, фамилия, номер телефона, идентификатор сотрудника и т. д. c ..

проблема, с которой я столкнулся сейчас, заключается в том, что функция сортировки вставкой не выполняет сортировку правильно, для первых 15 строк файла csv она как бы отсутствует, но ближе к концу запускается чтобы странно их отсортировать, компиляция не показывает ошибок, хотя ..

Я думал, что выложу это здесь, возможно, некоторые свободные sh глаза могли бы обнаружить проблему! заранее спасибо

вот код:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <conio.h>
#include <string.h>


// DEFINE
#define CSV_FILE_TO_READ "TPP_TP_Data_2019_base.csv"


// ============================
// GLOBAL VARIABLES


typedef struct node
{
    char Nom[50];
    char Prenom[50];
    char Initials[50];
    char Mobile[50];
    char Classe[50];
    char TriInitial[50]; // change into int
    char TriAleatoire[50];  // change into float

    struct node *next;
} node;

node *HEAD=NULL;

// ============================
// FONCTION PROTOTYPE DECLARATIONS

node * Read();
void Display(node *);
void InsertionSort(node **);
void sortedInsert(node** ,node*);

// ============================
// MAIN

int main()
{

    HEAD=Read();
    Display(HEAD);
    InsertionSort(&HEAD);
    printf("\n\n\n");
    Display(HEAD);


    return 0;
}

// ============================
// FUNCTIONS


node * Read() // done
{

    FILE *fPointer;
    fPointer = fopen(CSV_FILE_TO_READ,"r");

    if (fPointer == NULL)
    {
        printf("\nCould not open file %s",CSV_FILE_TO_READ);
        exit(1);
    }

    //reading the file and creating liked list

    char parsedLine[100];
    node *head = NULL;
    node *p = NULL;


    while(fgets(parsedLine, 100, fPointer) != NULL)
    {

        node * temp=malloc(sizeof(node));

        char *getNom = strtok(parsedLine, ";");
        strcpy(temp->Nom, getNom);

        char *getPrenom = strtok(NULL, ";");
        strcpy(temp->Prenom, getPrenom);

        char *getInitials = strtok(NULL, ";");
        strcpy(temp->Initials, getInitials);

        char *getMobile = strtok(NULL, ";");
        strcpy(temp->Mobile, getMobile);

        char *getClasse = strtok(NULL, ";");
        strcpy(temp->Classe, getClasse);

        char *getTriInitial = strtok(NULL, ";");  // change function into int getter scanf("%d",&(temp->data));
        strcpy(temp->TriInitial, getTriInitial);

        char *getTriAleatoire = strtok(NULL, ";");  // change function into a float getter
        strcpy(temp->TriAleatoire, getTriAleatoire);


        temp->next = NULL;

        if(head == NULL) // if first is empty, then make temp the first node
        {
            head = temp;
        }
        else
        {
            p=head;
            while(p->next != NULL)
                p=p->next;
            p->next=temp;
        }
    }

    fclose(fPointer);

    return head;
}


void InsertionSort(node **head_ref)   // function to sort a singly linked list using insertion sort
{

            // Initialize sorted linked list
            node *sorted = NULL;

            // Traverse the given linked list and insert every node to sorted

            node *current = *head_ref;
            while (current != NULL)
            {
                // Store next for next iteration
                node *next = current->next;

                // insert current in sorted linked list
                sortedInsert(&sorted, current);

                // Update current
                current = next;
            }

            // Update head_ref to point to sorted linked list
            *head_ref = sorted;

}


void sortedInsert(node** head_ref,node* new_node)
        {
            node* current;
            // Special case for the head end
            if (*head_ref == NULL || (*head_ref)->Prenom >= new_node->Prenom)  // inject sort parameter into data
            {
                new_node->next = *head_ref;
                *head_ref = new_node;
            }

            else
            {
                // Locate the node before the point of insertion
                current = *head_ref;
                while (current->next!=NULL && current->next->Prenom < new_node->Prenom)
                {
                    current = current->next;
                }
                new_node->next = current->next;
                current->next = new_node;
            }
        }




void Display(node * head)  // prints out the contents of the linked list // done
{
    node *temp=head;
    while(temp!=NULL)
    {
        printf("%s %s %s %s %s %s %s \n",temp->Nom,temp->Prenom,temp->Initials,temp->Mobile,temp->Classe,temp->TriInitial,temp->TriAleatoire);
        temp = temp->next;
    }
    printf("\n");
    printf("===========================================");

}
...