My problem is deleting a node from linked list.
I have two structs :
typedef struct inner_list
{
int count;
char word[100];
inner_list*next;
}
m
pointer is not set to any valid address before you dereference it and your program runs into undefined behavior.
In order to fix your implementation use two pointers - one onto the current element and the other to the previous one and update both of them as you traverse the list. You'll have to treat cases with zero and oneelemenats as special - be careful.
Your if condition that is checking for the word, isn't it to supposed to be the following:
if(strcmp(temp->word, num)==0)
?
I don't think you are freeing your inner_list
. You will get a memory leak.
try this (only for the outer list, it wont release the inner one):
void delnode(outer_list *head,char num[100])
{
outer_list *temp, *m. *helper;
temp=head;
while(temp!=NULL)
{
if(strcmp(temp->word,num)==0)
{
if(temp==head)
{
head=temp->next;
free(temp);
return;
}
else
{
m = temp;
temp = temp->next;
helper->next = temp; //link the previous item
free(m);
return;
}
}
else
{
helper = temp;
temp= temp->next;
}
}
printf(" ELEMENT %s NOT FOUND ", num);
}
There's a big problem in that if you end up needing to delete the first element of the outer list, you never pass back the new head of the list. Your origuinal code needs changing as follows (also put in all the other good suggestions):
void delnode(outer_list **tbd,char num[100]) // pass a pointer to tbd
{
outer_list *temp, *m;
temp = *tbd;
while(temp!=NULL)
{
if(strcmp(temp->word,num)==0)
{
if(temp==*tbd)
{
// Delete the inner list here
*tbd=temp->next;
free(temp);
return;
}
// rest of function
You'd call it like this:
outer_list* myList;
// lots of code including initialising and adding stuff to the list
delnode(&mylist, wordtoDelete); // note the '&' sign
FIX#1 (optional) - it is a good practice to initialize all variables. note that in this specific case since you have handles the head secanrio then you should not have a problem becuase m is set to temp later on, but still..
FIX#2 - make sure you delete the inner list completely before you free a node.
Here is the code (untested, sorry)
void delnode(outer_list *head,char num[100])
{
outer_list *temp, *m;
m=temp=head; /*FIX #1*/
while(temp!=NULL) {
if(strcmp(temp->word,num)==0) {
if(temp==head) {
head=temp->next;
delinner(temp->inner_list); /* FIX#2 */
free(temp);
return;
} else {
m->next=temp->next;
delinner(temp->inner_list); /* FIX#2 */
free(temp);
return;
}
} else {
m=temp;
temp= temp->next;
}
}
printf(" ELEMENT %s NOT FOUND ", num);
}
void delinner(inner_list *head) { /* FIX#2 */
inner_list *temp;
temp=head;
while(temp!=NULL) {
head=temp->next;
free(temp);
temp=head;
}
}