clinked-listdoubly-linked-listtailfunction-definition

Deleting selected element in a doubly linked list


I have written a code on deleting a node by comparing its data from the data given. If equal, it deletes the node. My problem is that my code will delete every node in the list except the last node, I couldn't figure out what I'm doing wrong, so I seeked the help as usual

Code is duly attached. Hope someone helps me.

(edit: the code has been modified in accordance with the mistakes)

int dl_delete_element(Dlist **head, Dlist **tail, int data)
{
    Dlist *temp,*prev;
    if(*head==NULL)
        return FAILURE;
    temp=*head;
    if(temp->data==data)
    {
        prev=*head;
        (temp->next)->prev=NULL;
        *head=temp->next;
        free(prev);
        return SUCCESS;
    }
    else
    {
        while(temp!=NULL)
        {
            if(temp->data==data)
            {
                prev=temp;
                (temp->prev)->next=temp->next;
                (temp->next)->prev=temp->prev;
                free(prev);
                return SUCCESS;
            }
            else
                temp=temp->next;
        }
        return DATA_NOT_FOUND;
    }
}

Solution

  • Let's try something simple.

    1. Find which element to delete.

       Dlist* cur = *head;
       while (cur != NULL && cur->data != data) 
           cur = cur->next;
       if (cur == NULL) 
           return FAILURE; // or DATA_NOT_FOUND? What other failures are there?
      
    2. Delete it.

       if (cur == *head) 
          *head = cur->next;
       else 
          cur->prev->next = cur->next;
      
       if (cur == *tail) 
          *tail = cur->prev;
       else 
          cur->next->prev = cur->prev;
      
       free(cur);
       return SUCCESS;
      

    Looks good? Caveat: this code is untested. If you find a bug, fix it!