funny and stupid solution with one assumption in C++

  • 0

    assumption: there is a value which was never been used in every node. (let's say INT_MIN)
    solution: move node by node and set INT_MIN for the node visited. if a node has INT_MIN value, the given linked list has a cycle.

     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
    class Solution {
        bool hasCycle(ListNode *head) {
            if(!head) return false;
            ListNode *node = head;
                if(node->val == INT_MIN){
                    return true;
                node->val = INT_MIN;
                node = node->next;
            return false;

Log in to reply

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