题解 | #判断链表中是否有环#
判断链表中是否有环
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) { //思路:首先定义两个变量,一个fast,一个slow //让fast 每次走两步,slow每次走一步 //当fast和slow相遇时,即是该链表存在环结构。 //如果该链表为无环结构,则当遍历完这个链表时也不会相遇。即是返回false。 ListNode low=head,fast=head; while(fast!=null&&fast.next!=null){ low=low.next; fast=fast.next.next; if(fast==low){ return true; } } return false; } }