LeetCode-141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题分析:本题采用快慢指针的方法最为简单,让快慢指针最开始在同一起点,让快指针每次走两步,让慢指针每次走一步,若快指针追上慢指针,则证明该链表有环。注意判断指针为NULL的情况。
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == NULL) return false;
for (ListNode *fast = head, *slow = head; fast!= NULL && fast->next != NULL;)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)return true;
}
return false;
}
};