簡體   English   中英

在C中刪除鏈表的第一個和最后一個元素

[英]Deleting first and last element of a linked list in C

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;

}

我正在尋找兩個單獨的函數來刪除鏈表的第一個和最后一個元素。 這是我試過的。 你有什么建議? 特別是首先刪除對我來說是個問題。

    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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM