Home > OS >  Tried appending multiple nodes in LinkedList c but it's just printing 1 node
Tried appending multiple nodes in LinkedList c but it's just printing 1 node

Time:11-15

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-----------

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();

}

CodePudding user response:

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.

  • Related