Link List Insertion a node

To insert a node in a linked list using C++, follow these steps:

  1. Create a new node: Declare a new node and allocate memory for it using the 'new' keyword. Set the data value of the new node to the desired value.

  2. Set the new node's next pointer: Set the 'next' pointer of the new node to the next node in the list. This ensures that the new node is linked correctly to the remaining nodes in the list.

  3. Update the previous node's next pointer: Locate the previous node in the list, which will be the node before the position where you want to insert the new node. Set the 'next' pointer of the previous node to the new node, effectively linking the new node to the list.

  4. Handle special cases: If you want to insert the new node at the beginning of the list, update the head pointer to point to the new node. Similarly, if you want to insert the new node at the end of the list, update the 'next' pointer of the last node to point to the new node.

Here is an example code snippet that demonstrates the insertion of a node in a linked list:

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

void insertNode(Node head, int value) {
    // Step 1: Create a new node
    Node* newNode = new Node;
    newNode->data = value;
    newNode->next = nullptr;

    // Step 2: Set the new node's next pointer
    newNode->next = *head;

    // Step 3: Update the previous node's next pointer
    *head = newNode;
}

int main() {
    Node* head = nullptr;

    // Insert nodes at the beginning of the list
    insertNode(&head, 3);
    insertNode(&head, 2);
    insertNode(&head, 1);

    // Print the linked list
    Node* temp = head;
    while (temp != nullptr) {
        cout << temp->data << " ";
        temp = temp->next;
    }

    return 0;
}

This code snippet inserts nodes at the beginning of the list. You can modify it to insert nodes at different positions or at the end of the list by updating the 'insertNode' function accordingly.