本文共 494 字,大约阅读时间需要 1 分钟。
思路:经典跑圈。
/** * 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) { ListNode fast=head; ListNode slow=head; while (true) { if (fast==null||fast.next==null||slow==null) { return false; } fast=fast.next.next; slow=slow.next; if (fast==slow) { return true; } } }}
耗时:348ms,中游