LeetCode141 question: Given a linked list, determine whether there are loops in the linked list.

  1. Circular linked list
    Given a linked list, 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 ring in the linked list. In order to represent the rings in a given linked list, we use 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). If pos is -1, there are no rings in the linked list. Note: pos is not passed as a parameter, just to identify the actual situation of the linked list.

If there is a ring in the linked list, return true. Otherwise, it returns false.

Example 1:

Insert picture description here

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

Example 2:

Insert picture description here

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

Example 3:
Insert picture description here

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
 

提示:
链表中节点的数目范围是 [0, 104]
-105 <= Node.val <= 105
pos 为 -1 或者链表中的一个 有效索引 。

Code:

/**
 * 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) {
    
    
        if(head == null){
    
    //判断链表是否为空
            return false;
        }
        ListNode fast = head;
        ListNode slow = head;

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

            fast= fast.next.next;//fsat每次走两步的原因是走两步在最快的情况下可以遇到
            slow = slow.next;
            
            if(fast == slow){
    
    //相遇时说明有环
                return true;
            }
        }
        return false;//循环结束,fast和slow还没遇到说明链表无环
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112711138