Having a hard time with linked lists.
I am new to C and I am having a hard time with linked lists (preferred Java lists much more).
Anyway, this function is supposed to insert a string into the linked list if it doesnt already exist. If the string does exist in the list, increase the value by 1.
When I run my code, I insert aaa 2 times and print the list to get...
STRING VALUE
aaa 2
But inserting aaa 2 times and bbb once gives...
STRING VALUE
bbb 3
I have spent an hour just rearranging code and trying different things but I am having a hard time. I got a lot of the function from my textbook.
Code:
int insertIt(char* string, ListNodePtr *sPtr){
ListNodePtr newPtr; /*pointer to new node*/
ListNodePtr previousPtr; /*pointer to previous node in list*/
ListNodePtr currentPtr; /*pointer to current node*/
newPtr = malloc(sizeof(ListNode)); /*creates node*/
if(newPtr != NULL) { /*is space available*/
newPtr->symbol = string; /*place string in node*/
newPtr->value = 1; /*place value in node*/
newPtr->nextPtr = NULL; /*node does not link to another node*/
previousPtr = NULL;
currentPtr = *sPtr;
while(currentPtr != NULL) {
if(currentPtr->symbol == string) { /*If symbol exists...*/
currentPtr->value = (currentPtr->value+1); /*increase value by 1*/
break;
}
else
previousPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
}
/*create new node at beginning of list*/
if(currentPtr == NULL) {
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else if(currentPtr->symbol != string)
{
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
}
else
printf("%s not inserted.\n", string); fflush(stdout);
return 0;
}/*end function insertIt*/
I really have no idea what I am doing here.