题解 | #判断链表中是否有环#
判断链表中是否有环
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) { //判断链表中是否有环,利用快慢指针法,快指针一次走两步,慢指针一次走一步,如果有环,一定会有快指针追上慢指针的情况,如果没有环,那么一定是快指针先出现空值,。。循环的终止条件要防止快指针出现空指针异常。 ListNode fast=head; ListNode slow=head; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; if(fast==slow){ return true; } } return false; } }