141. Linked List Cycle[Easy]
141. Linked List Cycle
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Constraints:
- The number of the nodes in the list is in the range [0, 104].
- -10^5 <= Node.val <= 10^5
- pos is -1 or a valid index in the linked-list.
Example

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
思路
快慢指针问题,如果是一个循环,快指针一定会追上满指针,如果不是那一定会遇到null,就结束
题解
public boolean hasCycle(ListNode head) {
// 空节点直接返回
if (head == null)
return false;
ListNode slow, fast;
slow = fast = head;
// 快指针下一个节点和下下一个节点都有值,就继续
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
// 这边是比地址,不然要是两个val一样,也是没法区分的
if (slow == fast)
return true;
}
// 出循环了代表不是一个圆
return false;
}

浙公网安备 33010602011771号