LeetCode-141-环形链表
思路
使用快慢指针,假如存在环,那么快指针就会先进入环,然后在环中的某个节点和慢指针相遇
代码
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null)return false;
//不同时设置为head,保证满足循环条件slow!=fast
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast){
if(fast==null||fast.next==null)return false;//不存在环
slow=slow.next;
fast=fast.next.next;
}
return true;
}