1

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It's giving me an error as follows : libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc. What might be the reason for it?
@Pressing_Keys_24_7 A bug somewhere in your other code. Hard to say what without seeing the code.
@Pressing_Keys_24_7 bad_alloc can mean that you've run out of memory. But that's unlikely given how much memory computers have, unless of course you have an infinite loop and just keep allocating more and more memory. If you can't figure it out then remove as much code as possible while still leaving the bug, and then post the complete program, someone will take a look at it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.