nix nix - 1 year ago 83
C++ Question

LinkedList only adds two elements in C++

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


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;

if(node->next == NULL)
node->next = temp;
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);



In the output, it only gives me value
9 and 10
i.e only the last 2 elements. Looks like it's just replacing the values. However, I am not getting it. For my
node I am already initializing it to next i.e
temp->next = NULL
And in
function, i am using an
if condition
to only add next node if its NULL.

Any suggestions?

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