I am working on a program in C for my class to prepend, append, insert, display items of a circular-list. I came across while loop functioning differently then a do-while loop for what to my mind would potentially output the same items. I am looking for an explanation to why the output is different with the code blocks below, thank you. If you have places were I can modify code to enhance it please let me know trying to build as much information as possible again Thank You.
Link to full code: Pastebin
while(temp != head)
{
cout << temp->data << " ";
temp = temp->next;
}
Output: Nothing
do
{
cout << temp->data << " ";
temp = temp->next;
}while(temp != head);
Output: 10 20
CodePudding user response:
A while
loop evaluates its condition before entering the body. So, a while
loop may run 0 iterations.
A do..while
loop evaluates its condition after leaving the body. So, a do..while
loop will always run at least 1 iteration.
Using a while
loop will not work in this situation, since the condition (temp != head)
will always be false before the 1st iteration. If the list is empty, head
will be NULL
, so temp
will then be set to NULL
, thus (NULL != NULL)
will be false. Otherwise, head
will not be NULL
, and temp
will be set to point at the same Node
that head
is pointing at, thus (temp != head)
will still be false.
Whereas, using a do..while
loop instead, the condition (temp != head)
will be false only after the last Node
in the list has been iterated.
So, using a do..while
loop is the way to go in this situation.
However, your code is not accounting for the possibility of an empty list (head
is NULL), so you need to add that check to avoid dereferencing a NULL
pointer, eg:
void displayData()
{
if (head) // <-- add this!
{
Node* temp = head;
do
{
cout << temp->data << " ";
temp = temp->next;
}
while (temp != head);
}
}
Also, your appendNode()
can be simplified:
void appendNode(int newVal)
{
Node** temp = &head;
if (head) {
do {
temp = &((*temp)->next);
}
while (*temp != head);
}
*temp = new Node;
(*temp)->data = newVal;
(*temp)->next = head;
}
CodePudding user response:
the while loop doesn't run because you set temp to point to head right before the while condition resulting in a false condition.
in the do while loop the code runs before checking the condition and that is why you see different results.
do
{
cout << temp->data << " ";
temp = temp->next;
}while(temp != head);
is the same as
cout << temp->data << " ";
temp = temp->next;
while(temp != head)
{
cout << temp->data << " ";
temp = temp->next;
}
for other recommendations: You can remove line 24 because later in the code newNode->next is given a new value.