Linked List Cycle【leetcode】
646 ワード
チェーンテーブルにループがあるかどうかを判断し、筆記試験問題を何度もやったことがある.
速いポインタ、遅いポインタを定義し、ループがあれば、彼らは最後に必ず出会う.
速いポインタ、遅いポインタを定義し、ループがあれば、彼らは最後に必ず出会う.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast, *slow;
if (head == NULL) return false;
slow = head;
fast = head->next;
while (fast != NULL && fast->next != NULL)
{
if (slow == fast) return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};