题解 | #判断链表中是否有环#
判断链表中是否有环
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 l1 = head; ListNode l2 = head; while(l2 != null && l2.next != null){ l1 = l1.next; l2 = l2.next.next; if(l1 == l2){ return true; } } return false; } } 两个快慢指针,一个每次走一步,一个走两步,如果相交,说明有环