Here's a quick example of how it could be done.
The code could be optimized quite a bit, and loading words from a file is not included. (Don't want to finish the whole assignment for you)
There's also an intentional bug somewhere in there
Code:
#include <stdio.h>
#include <string.h>
typedef struct
{
char* word;
int count;
void* next;
} wordlist;
// if the list contains the word to scan for return pointer to that node
// Otherwise return NULL
wordlist* find_word(wordlist* list, char* word)
{
wordlist* current = list;
while(current)
{
if(strcmp(current->word, word) == 0)
return current;
current = current->next;
}
return NULL;
}
// adds word to the list
// returns a pointer to the newly added word
wordlist* add_word(wordlist* list, char* word)
{
wordlist *current=list, *tmp=NULL;
while(current)
{
tmp = current;
current = current->next;
}
current = malloc(sizeof(*current));
current->word = word;
current->count = 1;
current->next = NULL;
if(tmp)
tmp->next = current;
return current;
}
// frees allocated memory
void delete_list(wordlist* list)
{
wordlist *current = list;
while(current)
{
current = current->next;
free(current);
}
}
int main()
{
char* words[] = { "this", ".", "is", ".", "a", ".",
"test", ".", "of", ".", "a", ".", "word", ".", "list" };
wordlist *list=NULL, *current=NULL, *max=NULL;
int i, numwords=15;
for(i=0; i<numwords; i++)
{
wordlist* tmp = find_word(list, words[i]);
if(tmp)
{
tmp->count++;
if(max->count < tmp->count)
max = tmp;
}
else
{
current = add_word(current, words[i]);
if(!list) list = current;
if(!max) max = current;
}
}
printf("most frequent word is: %s (%d times)\n", max->word, max->count);
delete_list(list);
return 0;
}