Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Traverse linked list using two pointers. Move one pointer by one and the other pointer by two. If these pointers meet at some node then there is a loop. If pointers do not meet then linked list doesn't have loop.

Note: We don't need to check if slow pointer is null, because fast pointer is alwasy ahead which make sure slow pointer is always not null.

Solution: Fast and slow pointer

bool hasCycle(ListNode *head) {
    ListNode *slow = head;
    ListNode *fast = head;

    while(fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast) return true;
    }

    return false;        
}

results matching ""

    No results matching ""