🌗 142. 环形链表 II

吞佛童子2022年6月9日
  • algorithm
  • list
小于 1 分钟

🌗 142. 环形链表 II

难度: 🌗

问题描述

img_12.png


解法

/**
 * 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) {
        // 思路:
        // 快慢指针 2(x + y) = x + y + nC 
        // x = m
        if(head == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                break;
            }
        }
        if(fast == null || fast.next == null) {
            return null;
        }
        // 有环
        slow = head;
        while(slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}

输出

img_13.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou