LeetCode142 Question: Circular Linked List II Given a linked list, return the first node where the linked list starts to enter the ring. If the linked list has no rings, null is returned.

  1. Circular Linked List II
    Given a linked list, return the first node where the linked list starts to enter the ring. If the linked list has no rings, null is returned.

In order to represent the rings in a given linked list, we use the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). If pos is -1, there are no rings in the linked list. Note that pos is only used to identify the ring, and will not be passed to the function as a parameter.

Note: It is not allowed to modify the given linked list.

Advanced:

Can you solve this problem using O(1) space?

Example 1:
Insert picture description here

输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。

Example 2:
Insert picture description here

输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。

Example 3:
Insert picture description here

输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
 
提示:

链表中节点的数目范围在范围 [0, 104] 
-105 <= Node.val <= 105
pos 的值为 -1 或者链表中的一个有效索引

Code:

/**
 * 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 fast = head;
        ListNode slow = head;

        while(fast != null && fast.next != null){
    
    

            fast= fast.next.next;//fsat每次走两步的原因是走两步在最快的情况下可以遇到
            slow = slow.next;

            if(fast == slow){
    
    //相遇时说明有环
                break;
            }
        }
        if(fast == null || fast.next == null) {
    
    
            return null;//循环结束,fast和slow还没遇到说明链表无环
        }
        //代码走到这说明有环,并且slow和fast相遇了
        slow = head;//slow从头开始走
        while(slow != fast) {
    
    
            fast = fast.next;//fast从相遇的地方开始走
            slow = slow.next;
        }
         return fast;//此时相遇时就是入环的第一个节点,返回slow或者fast
    }
}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112727638