用快慢指针判断是否存在环
https://leetcode-cn.com/problems/linked-list-cycle/
//结点定义
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr) return false;
ListNode *slow = head, *fast = head->next;
while (slow != fast) {
if (fast == nullptr || fast->next == nullptr) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
如果存在环,返回环的入口
https://leetcode-cn.com/problems/linked-list-cycle-ii/