Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tried appending multiple nodes in LinkedList c++ but it's just printing 1 node

I tried appending multiple nodes in LinkedList c++ but it is just printing 1 node as I run it. Kindly review it, and help me fix it.

#include <iostream>
using namespace std;

//here is the node

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

// ————here is linkedlist———–

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class LinkedList {
private:
    Node* head;


public:

    LinkedList()
    {
        head = NULL;
    }

//———– append function ————

    void appendNode(int d)
    {
        Node* newNode = new Node;
        Node* nodePtr;

        newNode->data = d;
        newNode->next = NULL;

        if (!head)
        {
            head = newNode;
            
        }
        else
        {
            nodePtr = head;
            while (nodePtr->next)
            {
                nodePtr = nodePtr->next;
                nodePtr->next = newNode;
            }
        }
    }

//————— display function————–

    void display()
    {
        
        Node* nodePtr;
        nodePtr = head;

        while (nodePtr != NULL)
        {
            cout << nodePtr->data << endl;
            nodePtr = nodePtr->next;
        }
    }

    
};

//————– main function ————-

int main()
{
    LinkedList ll;

    ll.appendNode(2);
    ll.appendNode(21);
    ll.appendNode(11);
    ll.display();

}

>Solution :

Change your while loop from:

while (nodePtr->next)
{
    nodePtr = nodePtr->next;
    nodePtr->next = newNode;
    ...
}

to

while (nodePtr->next)
{
    nodePtr = nodePtr->next;
    ...
}
nodePtr->next = newNode;

Also, in C++ use nullptr instead of NULL.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading