Pressing_Keys_24_7
Pressing_Keys_24_7

Reputation: 1863

Generating a node for a linked list inside a for loop in c++

I am trying to generate a node for a linked list inside a for loop. I have defined the nodes for the head, tail and a temporary node(which stores the data). But when I include it inside a for loop and print the results, it does not return anything. Any suggestions on how can I improve my code?

private:
    Node *head;
    Node *tail;
}; 

Upvotes: 1

Views: 556

Answers (1)

john
john

Reputation: 87959

If you are creating a list of 100 nodes, then you need to allocate 100 nodes, not just one. Move new Node inside your loop, like this

void createNode(int value)
{
    for (int i = 0; i<100; i++) {

        node *temp = new Node;
        temp->data = i;
        temp->next = nullptr;

        if (head == nullptr)
        {
            head = temp;
            tail = temp;
        }
        else
        {   
            tail->next = temp;
            tail = temp;
        }
    }

Of course allocating 100 nodes in a function called createNode isn't a good idea either, but I guess you are just experimenting.

Upvotes: 3

Related Questions