THE
問題
成し遂げる
アイデア
リングを判断し、速いまたは遅いポインタを使用して進みます。高速ポインタは一度に2回移動し、低速ポインタは一度に1グリッド移動します。リングがある場合は、それが一致する必要があり、一致する場合は、終了する時間です。
- 速い、遅いを定義する
- while(fast!&& fast.next!== NULL)
-
- 高速=高速+2
-
- 遅い=遅い+1
-
- if(fast == slow)はtrueを返します
- falseを返します。
まとめと考察
- next.nextが境界を越えないことをどのように保証するかに注意してください。
コード
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
// make sure next is not null that make next.next is not null.
fast = fast->next->next;
slow = slow->next;
if(fast == slow ) return true;
}
return false;
}
};