Skip to main content

🟡 剑指 Offer II 022. 链表中环的入口节点

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

/** * 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 l = head;        ListNode r = head;
        while (r != null) {            r = r.next;            l = l.next;            if (r != null) {                r = r.next;            }
            if (l == r) {                break;            }        }        if (r == null) {            return null;        }        l = head;        while (l != r) {            l = l.next;            r = r.next;        }        return l;    }}