Hacky C++ O(n) time O(1) space (well, sort of...)


  • 0
    Y
    class Solution {
    public:
        static bool wasHere(ListNode* n) {
            return ((intptr_t)n->next & 0x1) != 0;
        }
    
        static void setWasHere(ListNode* n) {
            n->next = (ListNode*)(((intptr_t)n->next) | 0x1);
        }
        
        static void resetWasHere(ListNode* n) {
            n->next = (ListNode*)((intptr_t)n->next & ~((intptr_t)0x1));
        }
        
        ListNode *detectCycle(ListNode *head) {
            if (!head) return nullptr;
            
            ListNode* res = nullptr;
            for (auto c = head;;) {
                auto n = c->next;
                
                if (!n) {
                    break;
                }
                if (wasHere(c)) {
                    res = c;
                    break;
                }
                setWasHere(c);
                c = n;
            }
            
            for (auto c = head; c; ) {
                if (c == res && !wasHere(c)) {
                    break;
                }
                resetWasHere(c);
                c = c->next;
            }
            
            return res;
        }
    };

Log in to reply
 

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