1

I was trying to create a linked list using a for loop but the 'new' in the for loop in the create() method didn't quite allocate a new slot to store new data. As a result, when I tried to print the list, I got an infinite loop. Can somebody tell me what's wrong here?

struct node
{
    double value;
    node * next_ptr;
    node(){}
    node(double val, node * p): value(val), next_ptr(p) {}
    ~node(){}

};

node * create()
{
    using namespace std;
    node temp = {0, nullptr};
    node * result;
    for(int i=1; i<5; ++i)
    {
        result = new node;
        result->value = i;
        result->next_ptr = &temp;
        temp = *result;
    }
    return result;
};
2
  • @WhozCraig: Thank you. You're right, the problem with my code was next_ptr kept pointing at one location (i.e., &temp). Commented Jul 16, 2015 at 0:49
  • ~node(){} Advice -- Leave it empty. A node isn't supposed to be destroying anything. The list that manipulates the nodes should be responsible for removing/deleting the nodes. Commented Jul 16, 2015 at 1:13

2 Answers 2

3

The reason you are probably getting an infinite loop is because in:

temp = *result;

you are copying the value of *result into a new object of type node, which is unrelated to the one you created.

What you want to do is store a pointer instead:

node* temp = nullptr;
node* result;
for(int i=0; i<5; ++i)
{
    result = new node;
    result->value = i;
    result->next_ptr = temp;
    temp = result;
}
return result;

Live demo


A part from the learning value, just stick to std::forward_list or std::list, for lists, instead. Or even better just use std::vector or other containers (depending on the use that you make of the container).

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

Comments

-1

a simple one to create linked in for loop

#include <iostream>
class LinkedList {
  public:
  int value;
  LinkedList * next;
};

int main()
{
  LinkedList *List = nullptr;
  LinkedList *head = List;
  LinkedList *prev;
  for (int i=0; i< 3;i++)
  {
    LinkedList *temp = new(LinkedList);

    temp->value = i;
    temp->next = nullptr;
    if (head == nullptr)
    {
      head = temp;
      prev = head;
    }
    else
    {
      prev->next = temp;
      prev = temp;
    }
  }

}

Comments

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.