Deleting a node from doubly linked list


How do you delete a node from doubly linked list? This is basically manipulations of links and freeing the memory for deleted node. If you are not already familiar with concepts of doubly linked lists, I would recommend you go through that first.

Deleting a node from doubly linked list.

struct dnode * delete( struct dnode *p, int node_no, int *val)
{
        struct dnode *temp ,*prev=NULL;
        int i;
        if ( node_no <= 0 || node_no > nodecount (p))
        {
                printf("Error! the specified node does not exist\n");
                exit(0);
        }
        if ( node_no == 0)
        {
                temp = p;
                p = temp->right;
                p->left = NULL;
                *val = temp->data;
                return(p);
        }
        else
        {
                temp = p ;
                i = 1;
                while ( i < node_no )
                {
                        i = i+1;
                        prev = temp;
                        temp = temp-> right ;
                }
                prev->right = temp->right;
                if(temp->right != NULL)
                        temp->right->left = prev;
                *val = temp->data;
                free(temp);
        }
        return (p);
}


Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: