Insertion of a node in a single linked list

Inserting a node in a singly linked list means adding a new node to the list at a specified position. Here's an example of how to insert a node in a singly linked list using C:

```
struct Node {
    int data;
    struct Node* next;
};

void insertNode(struct Node** headRef, int position, int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;

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

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

In this code, we first create a new node `newNode` with the given value. We then check if the position is 1. If it is, we make the new node the new head of the list by setting its `next` pointer to the current head and updating the head pointer. If the position is not 1, we traverse the list to find the node at the position just before the insertion 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 insertion point, we update its `next` pointer to point to the new node, and we update the new node's `next` pointer to point to the node that used to be at the insertion point. This effectively inserts the new node into 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