Leetcode 环形链表Ⅱ

在这里插入图片描述

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

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

猜你喜欢

转载自blog.csdn.net/weixin_43812609/article/details/109004875
今日推荐