leetcode 141 环形链表

题目描述:

leetcode 141 环形链表

链接https://leetcode-cn.com/problems/linked-list-cycle/

代码:

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        //快慢指针法
        ListNode slow = head;
        ListNode fast = head.next;
        //无环 跳出循环
        while(fast.next != null && fast.next.next != null){
        	//有环 就会相遇
            if(slow == fast){
                return true;
            }
            //慢指针走一步
            //快指针走两步
            slow = slow.next;
            fast = fast.next.next;
        }
        return false;
    }
}
上一篇:leetcode 141 环形链表


下一篇:leetcode 141环形链表(快慢指针)