题解 | #判断链表中是否有环#
判断链表中是否有环
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 && slow != null) {
if (fast.next == null) { // 判个空,防止异常
return false;
}
fast = fast.next.next; // 快指针一次走两步
slow = slow.next; // 慢指针一次走一步
if (fast == slow) { // 快慢指针一旦碰头,就表示有环
return true;
}
}
return false;
}
}
查看17道真题和解析