文章目录 题目描述思路 & 代码 题目描述 常见题,用上了久违的快慢指针 思路 & 代码 举个例子就能明白了:我和汽车,进行一场比赛,跑道可能是环形跑道,也可能是直道。直道的话,将会以汽车撞到终点为结束( fast == null),也就是非环弯道的话,汽车总会在某个时刻,与我擦肩而过,代表领先我整整一圈,此时,我就能确定这肯定是一个环形跑道。“我” 就是 slow,“汽车” 就是 fast /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null){ return false; } // 使用快慢指针 ListNode slow = head, fast = head; while(fast.next != null && fast.next.next != null){ // fast一趟两次,slow一趟一次 if(fast.next == slow || fast.next.next == slow){ return true; } slow = slow.next; fast = fast.next.next; } return false; } } 无注释 + 优化版 public class Solution { public boolean hasCycle(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if(slow == fast) { return true; } } return false; } }