J'essaie fondamentalement de créer une liste chaînée à partir d'un fichier texte et d'ajouter un nouveau membre chaque fois que les mots sont différents, et d'incrémenter le compte si les mots sont identiques (affectation hw). Je pensais que je l'ai fait correctement, mais il semble ajouter un membre, peu importe quoi. Je me demande si je traverse la liste incorrectement pendant que je recherche? Voici mon code. Des pensées? Merci!Listes chaînées simples dans C
LIST *CreateList(FILE *fp)
{
char input[LINE_LEN];
LIST *root= NULL; /* contains root of list */
size_t strSize;
LIST *newList; /* used to allocate new list members */
int same; /* if string is same */
while (fscanf(fp, BUFFMT"s", input) != EOF) {
strSize = strlen(input) + 1;
if (root == NULL) {
if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) {
printf("Out of memory...");
exit(EXIT_FAILURE);
}
if ((newList->str = (char *)malloc(sizeof(strSize))) == NULL) {
printf("Not enough memory for %s", input);
exit(EXIT_FAILURE);
}
memcpy(newList->str, input, strSize); /*copy string */
newList->count = START_COUNT;
newList->next = NULL;
root = newList;
}
/* if not root node, add node, or increment count */
else {
same = ListSame(newList, input);
if (same == 1) {
root->count++;
}
else {
if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) {
printf("Out of memory...");
exit(EXIT_FAILURE);
}
if ((newList->str = (char *)malloc(sizeof(strSize))) == NULL) {
printf("Not enough memory for %s", input);
exit(EXIT_FAILURE);
}
memcpy(newList->str, input, strSize); /*copy string */
newList->count = START_COUNT;
newList->next = root->next;
root->next = newList;
}
}
}
return root;
}
int ListSame(LIST *head, char *input)
{
LIST *start = head;
for (; start != NULL; start = start->next) {
if (strcmp(head->str, input) == 0) {
return 1;
}
}
return 0;
}
est sensible à la casse? Essayez d'utiliser strictmp() sinon. – vpram86
votre code serait plus facile à suivre si vous utilisiez la «séparation des préoccupations»; c'est-à-dire, extraire le code de liste du code d'analyse de fichier ... –
'BUFFMT" s "semble incorrect. 'BUFFMT"% s "' peut-être? –