LeetCode 142. 环形链表 II
https://leetcode-cn.com/problems/linked-list-cycle-ii/
这个题跟今天LeetCode的每日一题是相同的思路,注意判断传入的链表是否为空以达到bug free~
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head == null){ return head; } ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ fast = head; while(fast != slow){ fast = fast.next; slow = slow.next; } return fast; } } return null; } }