Posts Detect Loop in linked list (geeksforgeeks - SDE Sheet)
Post
Cancel

Detect Loop in linked list (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given the head of a singly linked list, the task is to check if the linked list has a loop. A loop means that the last node of the linked list is connected back to a node in the same list. So if the next of the last node is null. then there is no loop.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {

    public static boolean detectLoop(Node head) {

        if(head == null || head.next == null)
            return false;

        Node slow = head;
        Node fast = head.next;

        while(fast != null && fast.next != null){

            fast = fast.next.next;
            slow = slow.next;

            if(slow == fast)
                return true;

        }

        return false;

    }

}
This post is licensed under CC BY 4.0 by the author.