Выбор параметров сортировки вставки для связанного списка, заполненного данными из CSV-файла в C - PullRequest
0 голосов
/ 22 января 2020

Я думаю, что этот вопрос настолько обычен, насколько это возможно, потому что я не нашел ничего похожего в Интернете.

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

Я получил программу для работы, но часть, где пользователь может выбрать столбец сортировки, я еще не написал; прямо сейчас параметр сортировки вводится внутри функции сортировки.

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

вот код:

// ============================
// BEGINNING OF CODE

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


// ============================
// DEFINE

#define FILE_TO_READ "TPP_TP_Data_2019_base.csv"


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

typedef struct node
{
    char Lastname[50];
    char Firstname[50];
    char Initials[50];
    char Mobile[50];
    char Class[50];
    char InitialSort[50];
    char RandomSort[50];

    struct node *next;
} node;

node *HEAD=NULL;


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

node * Read();

void Display(node *);

void Sort();
void InsertionSort(node **);
void sortedInsert(node** ,node*);


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

int main()
{
    HEAD=Read();
    Display(HEAD);
    printf("\n\n\n");

    Sort();

    printf("\n\n\n");
    InsertionSort(&HEAD);

    return 0;
}

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


node * Read()
{

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

    if (fPointer == NULL)
    {
        printf("\nCould not open file %s",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->Lastname, getNom);

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

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

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

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

        char *getTriInitial = strtok(NULL, ";");
        strcpy(temp->InitialSort, getTriInitial);

        char *getTriAleatoire = strtok(NULL, ";");
        strcpy(temp->RandomSort, 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 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->Lastname,temp->Firstname,temp->Initials,temp->Mobile,temp->Class,temp->InitialSort,temp->RandomSort);
        temp = temp->next;
    }
    printf("\n");
    printf("===========================================");

}


void Sort()
{
    char SortParameter;
    // declare SortChoice here;

    printf("\n Enter sort Parameter : ");
    printf("\n P - Firstname");
    printf("\n N - Lastname");
    printf("\n I - Initials");
    printf("\n M - Mobile");
    printf("\n C - Class");
    printf("\n X - Tri Initial");
    printf("\n Z - Tri Aleatoire");

    printf("\n Your Choice : ");
    fflush(stdin);
    SortParameter=getch();

    /*
    switch(SortParameter)
    {
        case 'P': SortChoice = ;
        case 'N': SortChoice = ;
        case 'I': SortChoice = ;
        case 'M': SortChoice = ;
        case 'C': SortChoice = ;
        case 'X': SortChoice = ;
        case 'Z': SortChoice = ;
    }
*/
    putch(SortParameter);
    printf("\n\n");
    printf("\n Sorting done, Here is the Sorted list : \n");
    InsertionSort(&HEAD);
    Display(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)->Firstname >= new_node->Firstname)
    {
        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 && strcmp(current->next->Firstname, new_node->Firstname)<0 )
        {
            current = current->next;
        }
        new_node->next = current->next;
        current->next = new_node;
    }
}


//=========================================================
...