给定一个链表,判断链表中是否有环(易理解)

代码:

/**
 * 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.next!=null&&fast.next.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast==slow) {
                return true;
            }
        }
        return false;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45755718/article/details/105212734