What is the method for deleting a node in a linked list in C language?

There are several methods to delete a node from a linked list in the C language.

  1. Iterate through to find and delete: First go through the list, locate the node to be deleted, then have the pointer of the previous node point to the next node, and finally free the memory space of the deleted node.
void deleteNode(struct Node** head_ref, int key) {
    struct Node* temp = *head_ref;
    struct Node* prev = NULL;
  
    if (temp != NULL && temp->data == key) {
        *head_ref = temp->next;
        free(temp);
        return;
    }
  
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }
  
    if (temp == NULL) {
        return;
    }
  
    prev->next = temp->next;
    free(temp);
}
  1. Two-pointer deletion: Using two pointers, one pointing to the current node and the other pointing to the node before the current node. Traverse the linked list, when the node to be deleted is found, update the pointer of the previous node to point to the next node of the current node, then free up the memory space of the deleted node.
void deleteNode(struct Node** head_ref, int key) {
    struct Node* temp = *head_ref;
    struct Node* prev = NULL;
  
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }
  
    if (temp == NULL) {
        return;
    }
  
    if (prev == NULL) {
        *head_ref = temp->next;
    } else {
        prev->next = temp->next;
    }
  
    free(temp);
}

It is important to pay attention to handling the situation of deleting nodes in a linked list, especially in regards to the head and tail nodes, as well as freeing the memory space of the deleted nodes to prevent memory leaks.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds