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

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

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;
}
全部评论
第十四行并不是很懂,为啥插入的元素和位置和值相等,才进行插入??
点赞 回复 分享
发布于 2022-01-20 12:01
打印函数有点问题,还需要把最后一个节点的val打印出来才对
点赞 回复 分享
发布于 2022-04-05 15:23

相关推荐

01-26 22:20
已编辑
门头沟学院 Java
Java抽象带篮子:项目很nb了,现在好好准备八股和算法吧,早点找实习,可以看看我的置顶帖子。帖子里写了怎么改简历,怎么包装实习经历,还有2个高质量可速成的项目话术,和我的牛客八股笔记专栏
点赞 评论 收藏
分享
评论
17
3
分享

创作者周榜

更多
牛客网
牛客企业服务