首页 > 代码库 > LeetCode Linked List Cycle

LeetCode Linked List Cycle

/** * 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) {        if (head == NULL) return false;        ListNode* fast = head;        ListNode* slow = head;        while (step(fast, 2) && step(slow, 1)) {            if (fast == slow) break;        }        return fast != NULL;    }        bool step(ListNode* &node, int n) {        while (node != NULL && n > 0) {            node = node->next;            n--;        }        return n == 0;    }};

水一发