Find if there is a ring in the singly linked list

/*Ring: There is a circular sub-linked list in a singly-linked list. There are two ways to solve the problem.
One: Starting from the current head, compare all the predecessor nodes every step forward to see if they are the same node. If so, there is a ring ,
Idea 2: Define the fast and slow pointers, the fast pointer takes two steps at a time, the slow pointer takes one step at a time, if the fast and slow pointers meet, there is a ring, otherwise there is no ring

The fast and slow pointer method is used here
*/

 //This is a defined node
  class ListNode {   
      int val;
      ListNode next;
      ListNode(int x) {         val = x;          next = null;      }  }




public class Solution {     public boolean hasCycle(ListNode head) {         if(head==null || head.next==null){//The empty linked list is bound to have no loop             return false;


         }
        //Define the fast and slow pointers
        ListNode fast = head;
        ListNode slow = head;//The fast and slow pointers start from the head 
        while(fast != null && fast.next != null){//traversal loop termination condition
            //traversal
            fast = fast.next.next;//Fast pointer takes two steps
            slow = slow.next;//Slow pointer takes one step
            if(fast == slow){//If the fast and slow pointers are equal,
                return true is found ;}
        }
        return false; //If the loop is not found at the end of the traversal, it means it was not found
    }
}

Guess you like

Origin blog.csdn.net/vivian233/article/details/114790315