题解 | #判断链表中是否有环#
判断链表中是否有环
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 p1 = head; ListNode p2 = head; while(p1 != null && p2 != null){ //因为要前进两步,所以要先判断p2.next是否为空,否则会越界 if(p2.next == null){ return false; } p1 = p1.next; p2 = p2.next.next; if(p1 == p2){ return true; } } return false; } }