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

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

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

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

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

void insertNode(Node *head, int val, int aim) {
    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;
    }
}

void delNode(Node **head, int aim) {
    if((*head)->val == aim) {
        Node *temp = (*head)->next;
        free(*head);
        *head = temp;
    }
    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;
    }
}

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

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

int main() {
    int num, headVal, delVal;
    // 读入输入中的节点数量注意数量包括头节点
    scanf("%d %d", &num, &headVal);
    // 定义头节点
    Node *head = (Node *)malloc(sizeof(Node));
    head->val = headVal;
    head->next = NULL;
    // 插入节点
    for(int i = 0; i < num - 1; i++) {
        int val;
        int aim;
        scanf("%d %d", &val, &aim);
        insertNode(head, val, aim);
    }
    // 删除节点
    scanf("%d", &delVal);
    delNode(&head, delVal);
    printList(head);
    freeList(head);
}

全部评论

相关推荐

10-07 20:48
门头沟学院 Java
听说改名就会有offer:可能是实习上着班想到后面还要回学校给导师做牛马,看着身边都是21-25的年纪,突然emo了了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务