题解 | #判断链表中是否有环# 双针竞逐
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
import java.util.*; /** * 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 = new ListNode(-1), low = new ListNode(-1); fast.next = head; low.next = head; while(fast != null && low != null){ if(low.next != null){ low = low.next; } if(fast.next != null){ fast = fast.next.next; }else{ break; } if(fast == low) return true; } return false; } }
该思路查看了题解,已经有相关的实现,可以参阅对应思路。