題目:node
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?ide
分析:spa
判斷有環的方式是設置兩個指針,一個快fast,一個慢slow,fast每次走兩步,slow每次走一步,若是fast和slow相遇,那說明有環指針
當fast和slow相遇時,slow確定沒有遍歷完鏈表,而fast已經在環內循環了n圈(n>=1),假如slow走了s步,那fast就走了2s步。fast的步數還等於s加上在環內轉了n圈。故有:it
2s = s + nrio
s = nrast
設整個鏈表長L,環入口點與相遇點距離爲a,起點到環入口點的距離爲x,則:class
x + n = s = nr = (n - 1)r + r = (n - 1)r + L - xList
x = (n - 1)r +(L - x - a)
循環
L - x - a爲相遇點到環入口點的距離。由此可知,從鏈表頭到環入口點等於n-1圈內環+相遇點到環入口點,因而咱們能夠從head開始另設一個指針slow2,兩個慢指針每次前進一步,它倆必定會在環入口點相遇。
代碼:
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) { ListNode *slow2 = head; while (slow2 != slow) { slow2 = slow2->next; slow = slow->next; } return slow2; } } return nullptr; } };