hi all I am new in c++ and writing a linked list program, my code is working fine , i just help to understand the traversal concept.
Below is my code my doubt is when we traverse a list to insert at the end we put the condition while (list->next != NULL) so that it points to the last node of the list. now when I was trying to display the list and had put same the condition , it printed till the second last node, and when I put this condition "while (list->next == NULL)" it didn't put anything. but the following code works which I found from google. Could anyone tell me how the 3 scenarios are different ? and also why the same "while condition" doesn't work for printing which works for inserting ?
[code]
void link_list :: print_list()
{
if (head==NULL)
{
cout<< "Empty list"<< endl;
}
else
{
int count = 0;
list=head;
//while (list->next != NULL)-- printed only till the second last node
// while (list->next == NULL) didn't print anything
while (list != NULL)
{
count++;
cout << "Node " << "value " << endl;
cout << count << " " << list->num << endl;
list = list->next;
}
}
}
while (list->next != NULL) // printed only till the second last node
That's because the condition is checked BEFORE the loop is executed. When list points to the last node, list->next is NULL, therefore the loop exits before printing the last node.
while (list->next == NULL) // didn't print anything
list->next is not NULL on the first node, therefore the condition is false and the loop doesn't execute.
while (list != NULL)
This execute correctly because list is not NULL until after list has been changed to list->next when printing the last node.
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
1) while (list->next != NULL) On each iteration will check if next node is NULL and if so, will stop iteratin. Else print current node.
That way last node will not be printed because next one is null. If you used do-while loop it would work correctly.
2) while (list->next == NULL) will print only if next node is null. So it will print only if your list contains one element and then it will try to access null pointer and probably crash.
@ all thanks I understood why it shouldn't be while(list->next !=NULL) as it will ignore the last element and won't print but isn't it same when we are inserting. shouldn't it also be teh condition while (list!=NULL) ?
No. The last node points to NULL, so you need to tell it to point to a new node. If you just went to the end of the list and made a new node, the last node would still point to nothing: