leetcode hot 21

解题思路:本题前面的思路和前一个相同,但是要找到对应的环开始的点,那就需要分析,结论就是:slow的指针继续走,同时一个从head出发的节点同时走,最后他们一定会在环开始点相遇。

/**
 * 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 null;
        ListNode dummy_head = new ListNode();
        dummy_head.next = head;
        ListNode fast = dummy_head.next.next;
        ListNode slow = dummy_head.next;
        while(fast!=slow){
            if(fast==null || fast.next==null || fast.next.next==null){
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode after = dummy_head;
        while(after!=slow){
            slow=slow.next;
            after=after.next;
        }
        return slow;
    }
}
posted @ 2025-03-05 20:20  kukudev  阅读(4)  评论(0)    收藏  举报