题目:
给一个链表,判断链表中是否存在环。
例 1:
输入:head = [3,2,0,-4] 输出:true
例 2:
输入:head = [1,2] 输出:true
例 3:
输入:head = [1] 输出:false
思路:
使用快慢指针解决该问题;
Code(Java):
public static boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = slow.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}