LeetCode 141. 环形链表 (快慢指针)

    科技2026-08-09  3

    环形链表

    /** * 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) { bool flag = false; ListNode *fast = head, *slow = head; while(fast && slow){ // 防止在起点的时候判断相遇 if(fast == slow && flag) return true; slow = slow->next; if(!fast->next) return false; else fast = fast->next->next; flag = true; } return false; } };
    Processed: 0.008, SQL: 9