题解 | #牛牛的链表删除#

牛牛的链表删除

https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f

#include <stdio.h>
#include <stdlib.h>

typedef struct LArr {
    int data;
    struct LArr *next;
}LArr,*Linklist;

//初始化链表函数
Linklist Initlist(Linklist L,int n)
{
    Linklist l,p;
    l = L;
    while(n)
    {
        p = (Linklist)malloc(sizeof(LArr)); 
        if(p == NULL)
            printf("error malloc");
        scanf("%d",&p->data);
        p->next = l->next;
        l->next = p;
        l = p;
        n--;
    }
    return L;
}

//删除链表中包含的指定值函数
Linklist Delete(Linklist L,int x)
{
    Linklist l,cur,p;
    l = L->next;
  	//此时p用于以防删除元素与第一个结点元素值相等
    p = L;
    while(l)
    {
        if(x == l->data)
        {
          	//cur用于保存当前结点,并将其释放
            cur = l;
            l = cur->next;
            p->next = l;
            free(cur);
        }
        else
        {
          	//p用于保存记录查找到相同结点时的上一个结点
            p = l;
            l = l->next;
        }
    }
    return L;
}

int main() {
    int n, x;
    Linklist L,p;
    scanf("%d%d",&n,&x);
    p = (Linklist)malloc(sizeof(LArr));
    if(p == NULL)
        printf("error malloc");
    L = p;
    L->next = NULL;
    //初始化链表函数
    L = Initlist(L,n);
    //删除链表中包含的指定值函数
    L = Delete(L,x);
    while(L->next)
    {
        L = L->next;
        printf("%d ",L->data);
    }
    return 0;
}
#删除链表中指定元素值#
全部评论

相关推荐

点赞 评论 收藏
分享
牛客nb666号:见天才的门槛罢了查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务