142. 环形链表 II

    科技2024-03-13  91

    https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-/

    数学推导,

     

    /**

     * 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) {

            ListNode fast=head,slow=head;

            while(true){

                if(fast==null||fast.next==null) return null;

                fast=fast.next.next;

                slow=slow.next;

                if(fast==slow) break;

            }

             fast=head;   

            while(fast!=slow){

                fast=fast.next;

                slow=slow.next;

            }

            return slow;

        }

    }

    Processed: 0.011, SQL: 9