题目描述:
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
解题思路:
快慢指针。
AC代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head)
{
if (head == nullptr) return false;
auto fast = head;
auto slow = head;
while (fast->next != nullptr and fast->next->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};