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

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

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));
                //node *tmp = (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);
    node *tmp2;
    tmp2 = head;
    tmp = head->next;
    while(tmp2){
        if(tmp->val == val_d){
            tmp2->next = tmp->next;
            tmp = tmp2->next;
            break;
        }
        else
            tmp = tmp->next;
            tmp2 = tmp2->next;

    }

    if(head->val == val_d){
        tmp = head->next;
        head = tmp;
    }

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

    }


    return 0;
}

全部评论
有很多问题,看下个修改版
点赞 回复 分享
发布于 2023-03-13 10:23 美国

相关推荐

点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
杨柳哥:这不是普通人,那这个钱的是天才
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务