insertion

insertion

by Mst.Kanij Fatima -
Number of replies: 0

#include <iostream>


class Node {

public:

    int data;

    Node* next;


    Node(int data) {

        this->data = data;

        this->next = nullptr;

    }

};


class LinkedList {

public:

    Node* head;


    LinkedList() {

        head = nullptr;

    }


    // Function to insert a node with given data after a specific node

    void insertAfter(Node* prevNode, int newData) {

        if (prevNode == nullptr) {

            std::cout << "Previous node cannot be null." << std::endl;

            return;

        }


        Node* newNode = new Node(newData);  // Create a new node

        newNode->next = prevNode->next;    // Set the new node's next to the next of the previous node

        prevNode->next = newNode;          // Update the next of the previous node to point to the new node

    }


    // Function to display the linked list

    void display() {

        Node* current = head;

        while (current != nullptr) {

            std::cout << current->data << " -> ";

            current = current->next;

        }

        std::cout << "nullptr" << std::endl;

    }

};


int main() {

    LinkedList linkedList;


    // Insert nodes at the beginning

    linkedList.head = new Node(1);

    Node* secondNode = new Node(2);

    Node* thirdNode = new Node(3);

    linkedList.head->next = secondNode;

    secondNode->next = thirdNode;


    std::cout << "Original Linked List:" << std::endl;

    linkedList.display();


    // Insert a new node with data 4 after the secondNode

    linkedList.insertAfter(secondNode, 4);


    std::cout << "\nLinked List after Insertion:" << std::endl;

    linkedList.display();


    return 0;

}