判断单链表有无环(leetcode 141)
一、快慢指针(最优解)
(1)快指针:每次走两个节点
(2)慢指针:每次走一个节点
(3)若两个指针相遇(相等),则一定有环。
(4)循环结束条件: fast指针遇空指针(未相遇)
(5)时间复杂度:O(n)
(6)空间复杂度:O(1)
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {
}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast<