题解 | 判断链表中是否有环
判断链表中是否有环
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 || head.next == null) {
return false;
}
// 双自增,只有当slow != fast,并且fast的next不为空死才表示不是环形
ListNode slow = head.next;
ListNode fast = slow.next;
while(fast != null) {
if(fast == slow) {
return true;
}
if(slow.next == null || fast.next == null || fast.next.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}

查看7道真题和解析