题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

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

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

typedef struct NODE{
    int val;
    struct NODE *next;

}node;

int main(){

    int n;
    scanf("%d", &n);

    node *head = (node*)malloc(sizeof(node));
    scanf("%d", &head->val);
    head->next = NULL;

    int val1, val2;
    node *tmp = (node*)malloc(sizeof(node));
    for(int i = 0; i < n - 1; i++){
        scanf("%d %d", &val2, &val1);
        tmp = head;
        while(tmp){
            if(tmp->val == val1){
                node *nod = (node*)malloc(sizeof(node));
                nod->val = val2;
                nod->next = tmp->next;
                tmp->next = nod;
                break;
            }
            tmp = tmp->next;
        }

    }

    int val_d;
    scanf("%d", &val_d);
    tmp = head;
    if(tmp->val == val_d){
        head = tmp->next;
        free(tmp);
    }else{
        while(tmp->next){
            if(tmp->next->val == val_d){
                node *to_delete = tmp->next;
                tmp->next = to_delete->next;
                free(to_delete);
                break;
            }
            tmp = tmp->next;
        }
    }

    tmp = head;
    while(tmp){
        printf("%d ", tmp->val);
        tmp = tmp->next;
    }

    return 0;
}

全部评论
修改版
点赞 回复 分享
发布于 2023-03-13 10:26 美国

相关推荐

10-09 09:39
门头沟学院 C++
HHHHaos:这也太虚了,工资就一半是真的
点赞 评论 收藏
分享
小火柴燃烧吧:接啊,接了之后反手在咸鱼找个大学生搞一下,量大从优
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务