Ring linked list (fast and slow pointer)

        Give you the head node head of a linked list, and judge whether there is a ring in the linked list. If there is a node in the linked list that can be reached again by continuously tracking the next pointer, then there is a cycle in the linked list. In order to represent the ring in the given linked list, the evaluation system internally uses the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). Note: pos is not passed as a parameter. Just to identify the actual situation of the linked list. Returns true if there is a cycle in the linked list. Otherwise, returns false.

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        //1、排除特殊情况
        if(head == null||head.next == null){
            return false;
        }
        //2、定义了快慢指针
        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;
        
    }
}

Guess you like

Origin blog.csdn.net/weixin_55229531/article/details/131690495