/* * @lc app=leetcode id=141 lang=java * * [141] Linked List Cycle */ // @lc code=start /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * 快慢指针,若链表中存在环,则快指针一次动两步,慢指针一次动一步,快指针一定会赶上慢指针 * * @param head * @return */ public boolean hasCycle(ListNode head) { ListNode slow = head, fast = head; boolean isCycle = false; while(fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if(fast == slow) { isCycle = true; break; } } return isCycle; } } // @lc code=end