Deletion of a node from a single linked list

Deleting a node from a singly linked list means removing a node from the list at a specified position. Here's an example of how to delete a node from a singly linked list using C:

```
void deleteNode(struct Node** headRef, int position) {
    if (*headRef == NULL) {
    printf("List is empty!");
    return;
    }

    struct Node* temp = *headRef;

    if (position == 1) {
        *headRef = temp->next;
        free(temp);
        return;
    }

    for (int i = 1; i < position-1 && temp != NULL; i++) {
        temp = temp->next;
    }
    if (temp == NULL || temp->next == NULL) {
        printf("Invalid position!");
        return;
    }
    struct Node* nodeToDelete = temp->next;
    temp->next = nodeToDelete->next;
    free(nodeToDelete);
}
```

In this code, we first check if the list is empty. If it is, we print an error message and return. If the list is not empty, we start by setting a temporary pointer `temp` to point to the head of the list. We then check if the position is 1. If it is, we simply update the head pointer to point to the second node in the list, free the memory occupied by the first node, and return. If the position is not 1, we traverse the list to find the node at the position just before the deletion point. We do this by starting at the head of the list and following the `next` pointer of each node until we reach the position. If we reach the end of the list before finding the position, we print an error message and return. Once we have found the node at the position just before the deletion point, we update its `next` pointer to point to the node that comes after the node we want to delete, and we free the memory occupied by the node we want to delete. This effectively removes the node from the list.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext