Insertion after a given element in a linked list

In this article we are going to see how we can insert a new node after a given node in a linked list.

Approach:

Since we are inserting a new node in between a already existing linked list, we will have to take that a previous node points towards our newly created linked list. Also the new node should point to the next node correctly in its next.

Example:

Suppose a linked looks like: 10->20->30->50->NULL

We want to insert '40' after '30' i.e the second node.

After insertion, our linked will look like: 10->20->30->40->50->NULL

Code:

#include<bits/stdc++.h>
using namespace std;

class Node{
    public:
    int data;
    Node *next;
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};

void traverseLinkedList(Node *node)
{
    while(node!=NULL)
    {
        cout<<node->data<<", ";
        node = node->next;
    }
}

void insertAfterGivenNode(int data, Node * node)
{
    //creation of new node with given data
     Node *newNode = new Node(data);     

     newNode->next = node->next;

     node->next = newNode;
}

int main()
{
    Node *head = new Node(10);

    Node *first = new Node(20);  

    Node *second = new Node(30);

    Node *third = new Node(50);

    head->next = first;
    first->next = second;
    second->next = third;    

    cout<<"Before Insertion: ";
    traverseLinkedList(head);

    insertAfterGivenNode(40, second);

    cout<<"\n\n After Insertion: ";
    traverseLinkedList(head);

    return 0;
}

Output:

Before Insertion: 10, 20, 30, 50, 

 After Insertion: 10, 20, 30, 40, 50,

This is how we can insert a new node after a given node in a linked list.

Did you find this article valuable?

Support Road To Code by becoming a sponsor. Any amount is appreciated!