P
pauldepstein
I don't understand the following code which is copied from a text. It
is the text's solution to the problem of determining if a linked list
is cyclic.
int DetermineTermination(node *head)
{
node *fast, *slow;
fast = slow = head;
while (1) {
if (!fast || !fast -> next)
return 0;
else if (fast == slow || fast -> next == slow)
return 1;
else {
slow = slow -> next;
fast = fast -> next -> next;
}
}
}
As I see it, while (1) just means while (true) and the while construct
isn't really needed.
However, the fast pointer is initially assigned to point to the same
value as the slow pointer.
So (as I see it), fast == slow will be true at the beginning, and the
value 1 will be returned.
So (as I see it), this function will simply return 1 almost always
unless the head pointer is null.
What am I missing?
In particular, I know that the text wants to implement the final else
statements -- slow = slow->next; etc. in order to update the slow and
fast pointers.
However, the final else only comes into play if fast == slow is false.
Why should fast == slow be false when fast is assigned to slow at the
beginning?
Thank you very much for your help.
Paul Epstein
is the text's solution to the problem of determining if a linked list
is cyclic.
int DetermineTermination(node *head)
{
node *fast, *slow;
fast = slow = head;
while (1) {
if (!fast || !fast -> next)
return 0;
else if (fast == slow || fast -> next == slow)
return 1;
else {
slow = slow -> next;
fast = fast -> next -> next;
}
}
}
As I see it, while (1) just means while (true) and the while construct
isn't really needed.
However, the fast pointer is initially assigned to point to the same
value as the slow pointer.
So (as I see it), fast == slow will be true at the beginning, and the
value 1 will be returned.
So (as I see it), this function will simply return 1 almost always
unless the head pointer is null.
What am I missing?
In particular, I know that the text wants to implement the final else
statements -- slow = slow->next; etc. in order to update the slow and
fast pointers.
However, the final else only comes into play if fast == slow is false.
Why should fast == slow be false when fast is assigned to slow at the
beginning?
Thank you very much for your help.
Paul Epstein