Program to delete a node from a linked list

August 29th, 2009  |  Published in Amit Sahrawat, Data Structures, Linux Sample Programs  |  1 Comment








/* Structure for a linked list*/
struct list{
    int num;
    struct list* next; /* pointer to next node in list*/
};

#define FREE(x) free(x);x=NULL;
/* Function to delete a node from a linked list, given the value for the node*/
int delete(struct list** head, int value)
{
    printf(“[%s][%d]\n”,__FUNCTION__,value);
    struct list* prev = NULL;
    struct list* pos= NULL;
    struct list* start = NULL;
    prev = *head;
    start = *head;
    int flag = 0;
    if(NULL == *head){
        printf(“List is Empty !! \n”);
        return -1;
    }
    else{
        if(value == (*head)->num)
        {   
            *head = (*head)->next;       
            FREE(prev);
            return 1;
        }else{
            while((*head)->next != NULL)
            {
                if(value == (*head)->num){
                    flag = 1;
                    pos = *head;
                    break;
                }
                prev = *head;
                *head = (*head)->next;
            }
            if(flag){
                prev->next = prev->next->next;
                FREE(pos);
            }else if(value == (*head)->num){
                pos = *head;
                FREE(pos);
                prev->next = NULL;               
            }           
        }
    }
    *head = start;
    return 0;   
}

/* Function to use the linked list functions*/
int main()
{
    struct list* node = NULL;
    struct list* new = NULL;
    int i;
    for(i=0; i < 10; i++)
    {
        insert(&node,i);
    }
     delete(&node,7);
     traverse(node);
}

Subscribe

Get articles in your inbox.

Enter your email address:

Join Us

Twitter Chatter


Recommendations

Archives

Categories