Reputation: 9066
I am trying to traverse a linked list and show the value of each node using node.I am using while loop here.But the problem is the last element of the linked list is not being printed.I had to print the last element seperately.
int print(){
printf("\ncurrent list is \n");
struct Node* showList;
showList=head;
while(showList->next !=NULL){
printf("%d ",showList->data);
showList=showList->next;
}
printf("%d",showList->data); // it prints the last element
printf("\n");
}
Upvotes: 1
Views: 120
Reputation: 75
You can use while(showlist != NULL) According to your condition, it won't enter into while loop for last element
Upvotes: 1
Reputation: 15310
You could just change the condition to:
while(showList != NULL)
Then your while
won't skip the last node. It is skipping the last node in the current state because obviously when you are at the last node then showList->next == NULL
and the loop won't execute even though the node contains a value.
Edit: Make sure you removed this line after the change or you'll have a problem:
printf("%d",showList->data); // it prints the last element
Alternatively you could use a for
loop:
for(showList = head; showList != NULL; showList = showList->next)
printf("%d ",showList->data);
Upvotes: 4
Reputation: 115
showList->next !=NULL
This condition is suitable for for loop
In the while loop you should use showList!=NULL
because in while loop showList points to NULL
after you exit the while loop
Upvotes: 1
Reputation: 244722
Presumably, the last node in your list has next
set to NULL
. That is typical for a linked-list implementation.
If this is the case in your implementation, the condition for the while
loop fails on the last node. In other words, (showList->next !=NULL)
evaluates to false when showList
is the last node.
To ensure that the last node gets printed, change the condition being tested. For example, you could simply test that showList
is non-null.
Upvotes: 2