Reputation: 23
This is suppose to delete all the nodes containing the data "last" which is the same as the string "name". It is not giving me an error, but it is not working properly.It deletes more than what it needs to delete.
struct node* mydelete(struct node *head) {
char name[21];
struct node *temp;
printf("---Please enter last name:");
scanf("%s", &name);
while (head->next != NULL) {
if (strcmp(head->last,name) == 0) {
temp = head;
head = head->next;
free(temp);
n--;
} else if (strcmp(head->next->last,name)==0) {
temp = head->next;
head->next = head->next->next;
free(temp);
n--;
} else
head = head->next;
}
return head;
}
Upvotes: 2
Views: 8376
Reputation: 375
return head
is wrong. When you move the head forward(to "next"), anything it passed will lost -- you maybe not free some of them, but you can't get them anymore. You should use temp pointer to hold first node in the list(after deletion), and return it at last.
And, don't forget if head == NULL.
.
Modified from your code:
struct node *first = NULL;
while(head != NULL)
{
if(strcmp(head->last,name)==0)
{ //delete head
temp = head;
head = head->next;
free(temp);
n--;
}
else
{ //delete head->next
if (first == NULL)
first = head;
if (head->next == NULL)
break;
if(strcmp(head->next->last,name)==0)
{
temp = head->next;
head->next = head->next->next;
free(temp);
n--;
}
else
head = head->next;
}
}
return first;
Upvotes: 1
Reputation: 2586
You do not need the else if
condition in your code of delete.
If more then one element is deleting it means that your list
contain more then one element with same name.
First check your list
contents .
Upvotes: 0
Reputation: 108
Firstly, your code crashes if you call with head == NULL
, which can very well happen (if your list is empty). So, check for that.
Secondly, there is no reason why you need to check the string name
against two different nodes of the list. Just skip the else if
branch.
Thirdly, if you want to delete just one node which matches your test, then break from the while cycle after you deleted it.
Upvotes: 0