2025年- H30-Lc138- 141.环形链表(快慢指针,快2慢1)---java版
1.题目描述
2.思路
弗洛伊德算法(快慢指针
3.代码实现
public boolean hasCycle(ListNode head) {//1.如果空节点或者只有一个节点,都说明没有环,返回falseif(head==null||head.next==null){return false;}//2.定义快慢指针,都从头节点出发ListNode slow=head;ListNode fast=head.next;// ListNode fast=head;//这会 直接跳过 while 循环,因为 slow == fast(它们是同一个节点),会立刻执行 return true; —— 即错误地判断有环!//让 fast 比 slow 先跑一步,这样才不会一开始就相等。//3.如果快慢指针不相等,执行快2慢1的操作while(slow!=fast){ //4.这个判断条件,是存在奇数节点链表的情况和偶数节点链表的情况,都是无环情况if(fast==null||fast.next==null){return false;}slow=slow.next;fast=fast.next.next;}return true;}