Insert node at middle of linked list in c++

Suppose we are inserted the following (1, 2, 3, 4, 5, 6, 7) node in a sequence. In this post are implement second approach.

insert linked list node in middle position
// Include header file
#include <iostream>

using namespace std;
// C++ Program for
// Insert linked list element at middle position

// Linked list node
class LinkNode
{
    public: int data;
    LinkNode *next;
    LinkNode(int data)
    {
        this->data = data;
        this->next = nullptr;
    }
};
class LinkedList
{
    public: LinkNode *head;
    // Class constructors
    LinkedList()
    {
        this->head = nullptr;
    }
    // Insert node in middle position
    void insert(int value)
    {
        // Create a new node
        LinkNode *node = new LinkNode(value);
        if (this->head == nullptr)
        {
            // First node
            this->head = node;
        }
        else
        {
            LinkNode *temp = this->head;
            LinkNode *middle = this->head;
            // Find the middle node
            while (temp->next != nullptr && 
                   temp->next->next != nullptr)
            {
                temp = temp->next->next;
                middle = middle->next;
            }
            // add node
            node->next = middle->next;
            middle->next = node;
        }
    }
    // Display linked list element
    void display()
    {
        if (this->head == nullptr)
        {
            return;
        }
        LinkNode *temp = this->head;
        // iterating linked list elements
        while (temp != nullptr)
        {
            cout << temp->data << " → ";
            // Visit to next node
            temp = temp->next;
        }
        cout << "NULL\n";
    }
};
int main()
{
    LinkedList *sll = new LinkedList();
    // Add node
    sll->insert(1);
    sll->insert(2);
    sll->insert(3);
    sll->insert(4);
    sll->insert(5);
    sll->insert(6);
    sll->insert(7);
    // 1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL
    sll->display();
    return 0;
}
 1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved