How to delete a specific node in a singly linked list w…

The steps to delete a specific node in a singly linked list in the C programming language are as follows:

  1. Firstly, it is necessary to find the node that comes before the one you want to delete.
  2. Point the next pointer of the previous node to the next pointer of the node to be deleted, effectively skipping the node to be deleted.
  3. Release the memory space of the node to be deleted.

The specific implementation is as follows:

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

// 定义链表节点结构体
typedef struct Node {
    int data;           // 数据域
    struct Node* next;  // 指针域
} Node;

// 删除指定节点
void deleteNode(Node* head, int value) {
    Node* prev = head;          // 前一个节点
    Node* current = head->next; // 当前节点

    // 遍历链表,查找要删除的节点
    while (current != NULL) {
        if (current->data == value) {
            break;
        }
        prev = current;
        current = current->next;
    }

    // 当前节点为NULL,表示没有找到要删除的节点
    if (current == NULL) {
        printf("Node with value %d not found.\n", value);
        return;
    }

    // 找到要删除的节点,删除
    prev->next = current->next;
    free(current);
}

// 打印链表
void printList(Node* head) {
    Node* current = head->next; // 从第一个节点开始打印

    // 遍历链表,依次打印节点的数据
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    printf("\n");
}

int main() {
    // 创建链表 1->2->3->4->5
    Node* head = (Node*)malloc(sizeof(Node));  // 头节点
    Node* node1 = (Node*)malloc(sizeof(Node)); // 第一个节点
    Node* node2 = (Node*)malloc(sizeof(Node)); // 第二个节点
    Node* node3 = (Node*)malloc(sizeof(Node)); // 第三个节点
    Node* node4 = (Node*)malloc(sizeof(Node)); // 第四个节点

    head->next = node1;
    node1->data = 1;
    node1->next = node2;
    node2->data = 2;
    node2->next = node3;
    node3->data = 3;
    node3->next = node4;
    node4->data = 4;
    node4->next = NULL;

    printf("Original list: ");
    printList(head);

    // 删除节点2
    deleteNode(head, 2);

    printf("List after deletion: ");
    printList(head);

    // 释放内存
    free(node4);
    free(node3);
    free(node2);
    free(node1);
    free(head);

    return 0;
}

In the above code, a linked list with 5 nodes is created, then the deleteNode() function is called to remove node 2, and finally the linked list is printed, resulting in:

Original list: 1 2 3 4 
List after deletion: 1 3 4 
bannerAds