Topic:
Given A linked list, determine if it has a cycle in it.
Can you solve it without using extra space?
Answer:
At first glance it's simple. My practice is to save the head pointer, and then the other pointer continues through until the head pointer is encountered. But I did not take into account the partial loopback situation:
To tell the truth, I didn't think of any good way. Until the discussion, found that there can be a pursuit of the problem of the idea to do: a slow pointer to run a step at a time, a quick pointer run two steps at a time. If there is a ring must be able to catch up.
So I wrote down:
Class Solution {public: bool Hascycle (ListNode *head) { if (head = = NULL | | head->next = NULL | | head->next- >next = = NULL) return false; listnode* slow = head->next; listnode* fast = head->next->next; while (slow! = NULL) { if (slow = = fast) { return true; } if (Fast->next->next = = NULL) { return false; } else { slow = slow->next; Fast = fast->next->next; } } return false; }};
Show Runtime Error ... Later found, when judging if (Fast->next->next = = null), I forgot to consider: if Fast->next = = NULL, then Fast->next->next became a wild pointer /c23>, and then else, if you assign a field pointer to fast, there's no end to it.
The IF (Fast->next->next = = null) is determined to be changed to if (Fast->next->next = = NULL | | fast->next = = NULL), or wrong ...
Then the basic skills exposed ... The condition "or" operation is a short-circuit operation . and Fast->next = = NULL is a condition that needs to be judged in advance , so it should be judged beforehand. Final AC version:
Class Solution {public: bool Hascycle (ListNode *head) { if (head = = NULL | | head->next = NULL | | head->next- >next = = NULL) return false; listnode* slow = head->next; listnode* fast = head->next->next; while (slow! = NULL) { if (slow = = fast) { return true; } if (Fast->next = = NULL | | fast->next->next = = NULL) { return false; } else { slow = slow->next; Fast = fast->next->next; } } return false; }};
"Leetcode from zero single brush" Linked list Cycle