题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <stdio.h>
typedef struct ListNode {
    int data;
    struct ListNode* next;
} ListNode;
int main() {
    ListNode* head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    //临时节点,表示插入节点
    ListNode* s;
    ListNode* temp;
    int n, digit, node1, node2, delete;
    scanf("%d", &n);
    //第一个节点值
    scanf("%d", &digit);
    s = (ListNode*)malloc(sizeof(ListNode));
    s->data = digit;
    s->next = head->next;
    head->next = s;
    //建立链表
    for (int i = 0; i < n - 1; i++) {
        temp = head->next;
        scanf("%d %d", &node1, &node2);
        s = (ListNode*)malloc(sizeof(ListNode));
        s->data = node1;
        //查找插入位置,使用头插法
        while (temp->data != node2 && temp != NULL) {
            temp = temp->next;
        }
        s->next = temp->next;
        temp->next = s;
    }
    //待删除节点值
    scanf("%d", &delete);
    temp = head;
    //找到待删除节点的前一个节点
    for (; temp->next != NULL; temp = temp->next) {
        if (temp->next->data == delete) {
            if (temp->next->next != NULL) {
                //待删除节点不是最后一个节点
                temp->next = temp->next->next;
            } else {
                //待删除节点位最后一个节点
                temp->next = NULL;
            }
        }
    }
    //输出
    while (head->next != NULL) {
        printf("%d ", head->next->data);
        head = head->next;
    }
    return 0;
}
查看6道真题和解析
