Deleting first and last element of a linked list in C

可紊 提交于 2019-12-10 19:28:27

问题


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 separate 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:


    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;

}


来源:https://stackoverflow.com/questions/2906636/deleting-first-and-last-element-of-a-linked-list-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!