首页 > 代码库 > 【Lintcode】102.Linked List Cycle

【Lintcode】102.Linked List Cycle

题目:

Given a linked list, determine if it has a cycle in it.

Example

Given -21->10->4->5, tail connects to node index 1, return true

题解:

Solution 1 ()

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head) {
            return false;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                return true;
            }
        }
        
        return false;
    }
};

 

【Lintcode】102.Linked List Cycle