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

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

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

// 沒看到有c的,我来发一个吧
// 由于是刷题,malloc、scanf等没判断返回值,见谅

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

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

static void insertNode(Node *head, int aim, int val) {
    while(head != NULL) {
        if(head->val == aim) {
            Node *temp = (Node*)malloc(sizeof(Node));
            temp->val = val;
            temp->next = head->next;
            head->next = temp;
            return;
        }
        head = head->next;
    }
}

static void delNode(Node **head, int aim)
{
    if ((*head)->val == aim) {
        Node *temp = (*head)->next;
        free(*head);
        *head = temp;
        return;
    }
    Node *iter = *head;
    while (iter->next != NULL) {
        if (iter->next->val == aim) {
            Node *temp = iter->next;
            iter->next = temp->next;
            free(temp);
            return;
        }
        iter = iter->next;
    }
}

static void printList(Node *head) {
    while(head != NULL) {
        printf("%d ", head->val);
        head = head->next;
    }
    printf("\n");
}

static void freeList(Node *head) {
    while(head != NULL){
        Node *next = head->next;
        free(head);
        head = next;
    }
}

int main() {
    int num = 0;
    int headVal = 0;
    int delVal = 0;
    scanf("%d %d", &num, &headVal);
    Node *head = (Node*)malloc(sizeof(Node));
    head->next = NULL;
    head->val = headVal;
    int i;
    for (i = 1; i < num; i++) {
        int aim = 0;
        int val = 0;
        scanf("%d %d", &val, &aim);
        insertNode(head, aim, val);
    }
    scanf("%d", &delVal);
    delNode(&head, delVal);
    printList(head);
    freeList(head);
    return 0;
}
全部评论
头结点不存储数值应该逻辑会更简单些
点赞 回复 分享
发布于 04-05 17:25 四川
打印函数有点问题,还需要把最后一个节点的val打印出来才对
点赞 回复 分享
发布于 2022-04-05 15:23
第十四行并不是很懂,为啥插入的元素和位置和值相等,才进行插入??
点赞 回复 分享
发布于 2022-01-20 12:01

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
评论
17
3
分享

创作者周榜

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