时间轴
时间轴
2026-03-13
init
链表,双指针
题目:
第一次相遇,快指针走了2 * k步,慢指针走了 k 步,记环外长度 m, 环长 L
快指针多走了n圈(nL)即k = nL, 即慢指针走了nL步
慢指针再走m步,则共走m+nL步到达m+nL= 环入口
注意下面那个循环不要用do while,因为一个链表可能是个循环链表,环外长度为0
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 | /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */struct ListNode { int val; ListNode *next; ListNode(int x) : val(x) , next(nullptr) { }};class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == nullptr) return nullptr; ListNode *low = head, *fast = head; do { if (fast->next == nullptr || fast->next->next == nullptr) return nullptr; fast = fast->next->next; low = low->next; } while (low != fast); // low == fast low = head; while (low != fast) { fast = fast->next; low = low->next; } return low; }}; |
