题目
链接
题解
/**
* 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) {
return false;
} else if (head.next == null) {
return false;
}
// 定义快慢指针
ListNode fast = head, slow = head;
while (fast != null && slow != null) {
// 同时移动
fast = fast.next;
slow = slow.next;
// 快指针每次移动两个节点,如果快指针追上了慢指针证明两者在绕圈
if (fast != null && fast.next != slow) {
fast = fast.next;
} else if (fast == null) {
return false;
} else {
return true;
}
}
return false;
}
}