编辑代码

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

// 定义链表节点结构
typedef struct Node {
    int data;           // 节点数据
    struct Node *next;  // 指向下一个节点的指针
} Node;

// 创建新节点
Node* createNode(int data) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在链表尾部插入节点
void insert(Node **head, int data) {
    Node *newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode; // 如果链表为空,新节点为头节点
        return;
    }
    Node *temp = *head;
    while (temp->next != NULL) {
        temp = temp->next; // 找到链表的最后一个节点
    }
    temp->next = newNode; // 将新节点插入链表尾部
}

// 删除链表中指定值的节点
void deleteNode(Node **head, int data) {
    if (*head == NULL) {
        printf("链表为空,无法删除!\n");
        return;
    }
    Node *temp = *head;
    Node *prev = NULL;

    // 如果要删除的是头节点
    if (temp != NULL && temp->data == data) {
        *head = temp->next; // 更新头节点
        free(temp);         // 释放原头节点内存
        return;
    }

    // 查找要删除的节点
    while (temp != NULL && temp->data != data) {
        prev = temp;
        temp = temp->next;
    }

    // 如果未找到要删除的节点
    if (temp == NULL) {
        printf("未找到值为 %d 的节点!\n", data);
        return;
    }

    // 删除节点
    prev->next = temp->next;
    free(temp); // 释放节点内存
}

// 打印链表
void printList(Node *head) {
    Node *temp = head;
    while (temp != NULL) {
        printf("%d -> ", temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
}

int main() {
    Node *head = NULL; // 初始化链表为空

    // 插入节点
    insert(&head, 10);
    insert(&head, 20);
    insert(&head, 30);

    printf("链表内容: ");
    printList(head); // 输出: 10 -> 20 -> 30 -> NULL

    // 删除节点
    deleteNode(&head, 20);
    printf("删除后的链表: ");
    printList(head); // 输出: 10 -> 30 -> NULL

    return 0;
}