LeetCode 141, 142. Linked List Cycle I+II
阿新 • • 發佈:2018-06-02
有環 TP clas 起點 urn 沒有 nbsp 快慢指針 list
判斷鏈表有沒有環,用Floyd Cycle Detection算法,用兩個快慢指針。
class Solution { public: bool hasCycle(ListNode *head) { if (!head) return false; ListNode *slow, *fast; slow=fast=head; do{ if (fast==NULL || fast->next==NULL) return false; slow = slow->next; fast= fast->next->next; }while(slow!=fast); return true; } };
142是141的進階,需要額外判斷環的起點。
詳見 https://leetcode.com/problems/linked-list-cycle-ii/solution/ 中的推導,不過裏面應該是 F=(n-1)(a+b)+b,因此從head和相遇點開始同時走,一定會在循環起點相遇。
class Solution { public: ListNode *detectCycle(ListNode *head) {if (!head) return NULL; ListNode *slow, *fast; slow = fast = head; do{ if (!fast || !fast->next) return NULL; slow = slow->next; fast = fast->next->next; }while(slow!=fast); ListNode *p=head, *q=slow;while(p!=q){ p = p->next; q = q->next; }; return p; } };
LeetCode 141, 142. Linked List Cycle I+II