views:

61

answers:

1
struct person 
{
    int age;
    char name[100];
    struct person *next;
};

void delfirst(struct person **p)// For deleting the beginning
{
    struct person *tmp,*m;
    m = (*p);
        tmp = (*p)->next;
    free(m);
    return;

}
void delend(struct person **p)// For deleting the end
{
    struct person *tmp,*m;
    tmp=*p; 
    while(tmp->next!=NULL)
    {
        tmp=tmp->next;
    }
    m->next=tmp;
    free(tmp);
    m->next = NULL;
    return;

}

I'm looking for two seperate functions to delete the first and last elements of a linked list. Here is what i tried. What do you suggest? Especially deleting first is so problematic for me.

+1  A: 
    if (!p || !(*p))
       return;
    struct person *tmp;
    tmp = (*p);
    (*p) = (*p)->next;
    free(tmp);
    return;

void delend(struct person **p)// For deleting the end
{
    if (!p || !(*p))
        return;
    if (!(*p)->next)
    {
        *p = NULL;    
    }
    struct person *tmp,*m;
    tmp=*p; 
    while(tmp->next->next!=NULL)
    {
        tmp=tmp->next;
    }
    free(tmp->next);
    tmp->next = NULL;
    return;

}
Andrey
@LuckySlevin: You might also check this site http://richardbowles.tripod.com/cpp/linklist/linklist.htm, a little clutter visual but teachs you how to delete items on linked list
Junior Mayhé
@Junior Mayhé great resource, i like that pictures
Andrey
Andrey thanks this solves my problem for deleting the first node.
LuckySlevin
@LuckySlevin check the edit. really it smells like homework, and if it is so i regret doing it for you. you should implement linked list at least once if you want to become real programmer
Andrey
@Andrey don't worry it's not homework. I just used to implement linked lists with global head and tail pointers. But this approach caused some problem, so i wanted to change my implementation of linked lists. I'm just trying to learn. Thanks for everything. @Junior Mayhe perfect resource. Although it is for C++, it gives me the idea about what i should do. Thanks
LuckySlevin