LeetCode——linked-list-cycle
Question
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution
判断一个链表是否有环,可以采用slow-fast的方法,也就是两个指针,一个指针一次性只走一步,一个指针一次性走两步,如果有环的话,他们毕定相遇,如果没有的话,fast肯定会走到空的。
Code
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
ListNode* slow = head;
ListNode* fast = head;
while (1) {
slow = slow->next;
// 因为fast走的比slow快,所以只需要判断fast就好了
if (fast->next != NULL && fast->next->next != NULL) {
fast = fast->next->next;
} else
return false;
if (slow == fast)
return true;
}
}
};