Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
第二次遇到这个题 竟然忘记怎么做:
/** * 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) { //the second time i saw this problem,but...i didn't remember how to solve it if (head == nullptr) return false; auto *slow = head; auto *fast = head->next; while (fast && fast->next && fast != slow) { slow = slow->next; fast = fast->next->next; } return fast == slow; } };
参考链接:https://leetcode.com/problems/linked-list-cycle/discuss/158085/beats-100(C++)