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

牛牛的链表删除

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

#include <stdio.h>
#include<malloc.h>

struct Node {
    int val;
    struct Node* next;
};

//大框架先创建
struct Node* createNode(int val) {
    struct Node* p = NULL;
    p = (struct Node*)malloc(sizeof(struct Node));
    if (p == NULL) {
        printf("创建失败!\n");
        return NULL;
    }
    p->val = val; //f赋值
    p->next = NULL;
    return p;
}


//在插入数据
void insertNode(struct Node* q, int val) {
    struct Node* p;
    p = (struct Node*)malloc(sizeof(struct Node));
    if (p == NULL) {
        printf("创建失败!\n");
        return ;
    }
    p->val = val;
    p->next = q->next;
    q->next = p;
}

void deleteNode(struct Node* head ,int data)  //data为要删除的结点数
{
    struct Node* p=head;
    struct Node* q=NULL;
    while(p!=NULL)
    {
        if(p->val==data)
        {
            if(p==head)  //要删除的是头结点
            head=p->next;
            else
            q->next=p->next;
        }
        q=p;  //备份
        p=p->next;
    }
}

//在打印结果

void printfNode(struct Node* p)
{
     struct Node* head =p;
     while(head->next!=NULL)
     {
         printf("%d ",head->val);
         head=head->next;
     }
}


int main() {
    int n, i,k;
    scanf("%d%d", &n,&k);
    int* arr = (int*)malloc(sizeof(int) * n);
    struct Node* head = createNode(0); //创建链表
    struct Node* p = head;

    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    head->val = arr[0];
    for (i = 1; i <= n; i++) {
        insertNode(p, arr[i]);
        p = p->next;
    }
    deleteNode(head, k);
    printfNode(head);

    free(p);
    return 0;
}

C语言刷题 文章被收录于专栏

自己从头开始刷的C语言

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 12:10
点赞 评论 收藏
分享
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
想按时下班的大菠萝在...:隔壁学校的,加油多投, 实在不好找可以下个学期开学找,把算法八股准备好,项目有空再换换
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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