LC 141. Linked List Cycle

Nilanjan Deb · April 1, 2020

I solved this problem for my academic course COMPUTER PROGRAMMING. Here I use simply two pointers namely fast and slow. According to their names fast moves two times faster than slow. Then I starting traversing through whole Linked list. If any time slow became equal to fast then we return true. Other wise contiue the process . If fast or next of fast became NULL then we return False. Simple Common sense Cycle exists iff fast never became NULL .

This is my CPP solution.

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


Dicussion Forum