überprüfen und aktualisieren Ich versuche, eine meiner Aufgaben zu beenden, und ich habe einige Probleme. Ich muss ein Programm erstellen, das struct verwendet, um eine Linkliste zu erstellen, in der ich Wörter hinzufügen muss. Wenn das Wort bereits in der verknüpften Liste ist, muss ich nur die Frequenz aktualisieren.wie ein Wort in der Linkliste hinzuzufügen, während auch die Häufigkeit des Wortes in c
ich dies bereits haben:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct words Words;
struct words{
char *word;
int freq;
Words *next;
};
/*
Inserts a copy of newWord into the list, in lexicographical order. If newWord is already
in the list, increment the freq member of the node. The function returns a pointer to
the list.
*/
Words *addWord(Words *headPtr, char* newWord){
Words *current = headPtr;
if(headPtr == NULL)
{
current->word = newWord;
current->freq = 1;
}
else
{
while(current != NULL)
if(strcmp(headPtr->word, newWord))
{
current->freq++;
return headPtr;
}
else
{
current->word = newWord;
current->freq = 1;
}
}
return headPtr;
}
//prints the words in the list, along with the frequency of each word
void printWords(Words *headPtr){
while(headPtr != NULL)
{
printf("%s: %d", headPtr->word, headPtr->freq);
headPtr = headPtr->next;
}
}
//frees the entire list. Note: Words **headPtr since the headPtr NULL upon return
void deleteList(Words **headPtr){
Words *current = *headPtr;
Words *next;
while(current != NULL)
{
next = current->next;
free(current);
current = next;
}
*headPtr = NULL;
}
int main(){
char word[20];
Words *list = NULL;
scanf("%s", word);
while(!feof(stdin)){
list = addWord(list, word);
scanf("%s", word);
}
printWords(list);
deleteList(&list);
}
In Klammern auf Ihre Blöcke, wenn sie mehr als eine Zeile haben, sonst sieht es verwirrend, den Compiler sicher versteht sofort, aber wenn nur Compiler Code lesen sollen, dann gibt es keinen Grund, die Funktion 'printWords()' aufzurufen. –