且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除在C链表的第一和最后一个元素

更新时间:2023-11-09 23:34:22

 如果(P!||!(* P))
       返回;
    结构*人TMP;
    TMP =(* P);
    (* P)=(* P) - >接着,
    免费(TMP);
    返回;无效delend(结构人** P)//删除结束
{
    如果(P!||!(* P))
        返回;
    如果(!(* P) - >接着)
    {
        * p值= NULL;
    }
    结构*人TMP,*米;
    TMP = * P;
    而(tmp->下一步 - >!下次= NULL)
    {
        TMP = tmp->接下来,
    }
    免费(tmp->下面);
    tmp->接着= NULL;
    返回;}

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.

    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;

}