0
votes

In my delete function for a circular doubly linked list when I enter the function with two nodes and delete one node it is changing my next node and previous node to null. This only happens when I enter the function with two nodes in the linked list. I am using breakpoints in eclipse and everything seems to be working until I end the function and return the temp. After that the next and previous for ptrLocal get set to NULL. Not really sure why.

Here is the function call

struct TCB_t del = delete_from_list(&RunQ);

Here is the function

struct TCB_t delete_from_list(struct  TCB_t **ptrLocal)
{
    struct TCB_t temp;

    if(*ptrLocal)
    {

        temp = **ptrLocal;
        temp.next = NULL;
        temp.previous =NULL;

        if(*ptrLocal == (*ptrLocal)->next->next)
        {
            *ptrLocal = (*ptrLocal)->next;
            (*ptrLocal)->next = *ptrLocal;
            (*ptrLocal)->previous =  *ptrLocal;
        }
        else if(*ptrLocal != (*ptrLocal)->next)
        {
            (*ptrLocal)->previous->next = (*ptrLocal)->next;
            (*ptrLocal)->next->previous = (*ptrLocal)->previous;
            *ptrLocal = (*ptrLocal)->next;
        }
        else
        {
            (*ptrLocal)->previous = NULL;
            (*ptrLocal)->next = NULL;
            *ptrLocal =NULL;
        }
        count--;
    }
    return temp;
}

After return temp ptrLocal->next and preLocal->previous are both set to null.

1
Do you ever malloc or free items? What do you do with the return value of the function? I don't see a problem (yet), but I think it is strange for you to return a copy of the deleted item because the actual item deleted will be leaked if you originally malloc'd it.JS1

1 Answers

1
votes

Your error is the last else. it applied when there is single node in the list.

In Circular linked list, next and previuos never shouldn't be NULL

Therefor if there is only 1 item, next and previous should point to itself.

Now your you should check like this:

if ((*ptrLocal)->next = (*ptrLocal)){ //delete the last item in the list, should NULL the pointer
   free(*ptrLocal); 
   *ptrLocal=NULL;   
}
else {
   (*ptrLocal)->previous->next = temp->next;
   (*ptrLocal)->next->previous = temp->previous;
   free(*ptrLocal);
}

I don't see the reason to check for two items:

For example A<->B<->A

And you delete B:

if you go to the else: you get A<->A which is still a circular list.