Search code examples
clinked-listdoubly-linked-list

How to delete node in double-linked-list by C programming?


struct someEvent
{
    int id;
    struct someEvent *prev;
    struct someEvent *next;
} * someEvent;

struct someEvent *someEventQueue = NULL;

int main(){

//There is some conditions. If passing all of conditions then It is inserted to someEventQueue.

struct someEvent **curr = &someEventQueue;

if ((*curr) != NULL)
{
    while ((*curr) != NULL)
    {
        //After some processes, I want to delete (*curr)

            if ((*curr)->prev == NULL && (*curr)->next == NULL)
            {
                //I don't know how to do this........................
            }
            if ((*curr)->prev != NULL)
            {
                (*curr)->next->prev = (*curr)->prev;
            }
            if ((*curr)->next != NULL)
            {
                (*curr)->prev->next = (*curr)->next;
            }
    
        curr = &(*curr)->next;
    }
}
}

I want to delete node which is presenting in someEventQueue. someEventQueue is double-linked-list. I tried to make a deleting node code. But, I failed. I don't know why but it returns segmentation fault. How to solve this problem?


Solution

  • To simply delete a node you can do this:

    // dnode is the node to delete
    if ((*dnode)->prev != NULL) {      // checking if this is the first
        (*dnode)->prev->next = (*dnode)->next;
        if ((*dnode)->next != NULL) {  // checking if this is the last
            (*dnode)->next->prev = (*dnode)->prev;
        }
    } else {                           // here the node is the first
        (*dnode) = (*dnode)->next;
        if ((*dnode) != NULL) {        // checking if he was the last
            (*dnode)->prev = NULL;
        }
    }
    

    Now your node is delete from the linked list, but take care to the positionnement of your cursor on the list and to free dnode.