这是道简单题,直接用快慢指针,代码如下
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
//遇到null则return false
if (fast == null || fast.next == null) {
return false;
}
//慢指针每次走一步
slow = slow.next;
//快指针每次走两步
fast = fast.next.next;
}
return true;
}
}
题目链接:题单 - 力扣(LeetCode)全球极客挚爱的技术成长平台