2

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;
}
2
  • Would you also post the test case and execution result? Commented Dec 1, 2013 at 7:03
  • I'm trying to delete all nodes that contain the "name" Commented Dec 1, 2013 at 19:57

3 Answers 3

1
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;
Sign up to request clarification or add additional context in comments.

1 Comment

@user3053814 I had a error: "bread" should be "break". Code has been corrected.
0

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.

Comments

0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.