给定一个链表,判断链表中否有环。
补充:
你是否可以不用额外空间解决此题?
详见:https://leetcode.com/problems/linked-list-cycle/description/
/** * 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; } ListNode *slow=head; ListNode *fast=head; while(fast&&fast->next) { slow=slow->next; fast=fast->next->next; if(slow==fast) { return true; } } return false; } };