Whenever you create a new node, you need to make sure new_node->next is NULL.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
I think the problem is that you are not setting the 'next' pointer of the last node to NULL. It cab be containing some garbage and giving unexpected results. Can you try this.
void add_to_end(int data)
{
cout << "add to end" << endl;
node *temp;
if (hd == NULL)
{
node *new_node;
new_node = new node;
new_node->data = data;
<strong>new_node->next = NULL</strong>;
//if I omit the next line then the print function works fine
hd = new_node;
}
else
{
for (temp = hd; temp->next != NULL; temp = temp->next){
cout << "for loop" << endl;
}
node *new_node;
new_node = new node;
new_node->data = data;
<strong>new_node->next = NULL</strong>;
//if I omit the next line then the print function works fine
temp->next = new_node;
}
}
edit:concurrent replies i guess. hope you got the point.
Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116