nix - 1 year ago 83

C++ Question

I am trying to learn linkedlist in c++, I am facing a problem as linkedlist is only adding 2 elements.

code:

`struct Node {`

int data1;

Node* next;

};

void firstElement(Node *&head, int d)

{

Node* temp = new Node;

temp->data1 = d;

temp->next = NULL;

head = temp;

}

void insert(Node *&node, int data)

{

Node* temp = new Node;

temp->data1 = data;

temp->next = NULL;

while(node)

{

if(node->next == NULL)

{

node->next = temp;

return;

}

node = node->next;

}

}

void display(Node *&node)

{

while(node != NULL)

{

cout << node->data1 << endl;

node = node->next;

}

}

int main()

{

Node* head;

firstElement(head, 1);

insert(head, 2);

insert(head, 3);

insert(head, 4);

insert(head, 5);

insert(head, 6);

insert(head, 7);

insert(head, 8);

insert(head, 9);

insert(head, 10);

display(head);

}

In the output, it only gives me value

`9 and 10`

`temp`

`temp->next = NULL`

And in

`insert()`

`if condition`

Any suggestions?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The problem comes from `insert`

function. It takes a `Node* &`

so as soon as you do

```
node = node->next;
```

in the loop, it will modify your original list.
Remove `&`

and your problem is solved :

```
void insert(Node* node, int data)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**