題目
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
解題之法
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) break;
}
if (!fast || !fast->next) return NULL;
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
};
分析
這個(gè)求單鏈表中的環(huán)的起始點(diǎn)是之前那個(gè)判斷單鏈表中是否有環(huán)的延伸, 還是要設(shè)快慢指針,不過這次要記錄兩個(gè)指針相遇的位置,當(dāng)兩個(gè)指針相遇了后,讓其一指針從鏈表頭開始,此時(shí)再相遇的位置就是鏈表中環(huán)的起始位置。