141. 环形链表
package leetcode; public class demo_141 { public boolean hasCycle(ListNode head) { //空链表也无环 if(head==null) {return false;} //快指针跑两个节点,慢指针跑一个节点 ListNode fast=head.next; if(head.next!=null) { fast=fast.next; } ListNode slow=head; while(fast!=null) { //如果存在环,则快指针一定会追上慢指针 if(fast==slow) { return true; } //如果不存在环,则快指针会先结束 if(fast.next!=null) { fast=fast.next.next; } else { return false; } slow=slow.next; } return false; } }
浙公网安备 33010602011771号