描述
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
相关题目
带环链表2 & 两个链表的交叉
代码实现
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
//快 慢 指 针
//快指针以慢指针二倍的速度移动,如果快慢指针指向同一地址,则返回true
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast = head.next;
ListNode slow = head;
while (fast != slow) {
if (fast == null || fast.next == null) {
return false;
} else {
fast = fast.next.next;
slow = slow.next;
}
}
return true;
}
}