I'm basically trying to create a linked list from a text file and add a new member every time the words are different, and increment the count if the words are the same (hw assignment). I thought I did it correctly, but it seems to add a member no matter what. I'm wondering if I'm traversing the list incorrectly while I search? Here is my code. Any thoughts? Thanks!
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;
}