Summary
Consider the following aspects:
If the linked list contains loop, the function must return true or else false
Let’s assume:
Function- detectloop()
Solution
//User function template for JAVA /* Node is defined as class Node { int data; Node next; Node(int d) {data = d; next = null; } } */ class Solution { //Function to check if the linked list has a loop. public static boolean detectLoop(Node head){ // Add code here Node slow=head; Node fast=head.next; while(fast!=null && fast.next!=null){ if(fast==slow) return true; slow=slow.next; fast=fast.next.next; } return false; } } |
Explanation:
Initialization of Pointers:
Two pointers, slow and fast, are initialized to the head of the linked list. The fast pointer is initially advanced by two steps, and the slow pointer by one step.
Loop Detection:
The code enters a loop where it checks for a loop using the condition fast != null && fast.next != null.
Answered by:> >koynakhare
Credit:> >GeekforGeeks
Suggested blogs:
>How to configure python in jmeter?
>How to mock a constant value in Python?
>Creating a pivot table by 6 month interval rather than year
>How to Install mariaDB client efficiently inside docker?
>Can I call an API to find out the random seed in Python `hash()` function?
>How remove residual lines after merge two regions using Geopandas in python?