代码实现:
快慢指针:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool hasCycle(struct ListNode *head) { // 快慢指针:快指针每次走两步,慢指针每次走一步,二者若重合则链表中有环,否则无环 struct ListNode *slow = head, *fast = head; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; if (fast == slow) { return true; } } return false; }