This is my solution. The time complexity is O(n), and I used constant space.

  • -3

    However, it's really a bad solution.

    class Solution {
        ListNode *detectCycle(ListNode *head) {
            ListNode *p = head;
            while (p) {
                p->val = -1234567;
                if (p->next && p->next->val == -1234567) return p->next;
                p = p->next;
            return NULL;

  • 0

    What is your question? Please state your question clearly.

  • 1

    You could have used Floyd Cycle detection algorithm which is faster than your method .
    Although, it seems more like you have used brute force?In fact, your solution is not feasible as it is "changing" the loop, if one is allowed to build the code again, they are likely to get an unexpected linked list.
    Not suitable for interview point of view.

  • 0

    very interesting algorithm...

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.