141. Linked List Cycle
Difficulty: Easy
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路
定义两个指针,同时从链表头结点出发,一个指针一次走一步,另一个指针一次走两步。如果快的指针追上了慢的指针,存在环;如果快的指针追上之前就走到了链表末尾,不存在环。
代码
[C++]
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
struct ListNode *slow = head->next;
if (slow == NULL)
return false;
struct ListNode *fast = slow->next;
while (fast != NULL && slow != NULL) {
if (fast == slow)
return true;
slow = slow->next;
fast = fast->next;
if (fast != NULL)
fast = fast->next;
}
return false;
}
};