[LintCode]Linked List Cycleシングルチェーンテーブルのループ

1781 ワード


Given a linked list, determine if it has a cycle in it.
ExampleGiven -21->10->4->5, tail connects to node index 1, return true
Challenge Follow up:Can you solve it without using extra space?
 
LeetCodeの原題は、私の前のブログLinked List Cycleを参照してください.
 
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    bool hasCycle(ListNode *head) {
        if (!head) return false;
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};