对于一个给定的链表,返回环的入口节点,如果没有环,返回null

该博客介绍了如何在给定的链表中找到环的入口节点,如果链表无环,则返回null。作者提供了使用Set来检测重复节点的解决方案,并提及了无需额外空间的解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:遍历链表,将节点存入Set,遇到重复节点即返回。

import java.util.*;
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null){
            return null;
        }
        Set set = new HashSet();
        set.add(head);
        while(head.next!=null){
            if(set.contains(head.next)){
                return head.next;
            }else{
                set.add(head.next);
                head=head.next;
            }
        }
        return null;
    }
}

补充:不用额外空间的解法


/**
 * 题目描述: 链表的入环节点,如果无环,返回null
 * Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
 * Follow up: Can you solve it without using extra space?
 * 思路:
 * 1)首先判断是否有环,有环时,返回相遇的节点,无环,返回null
 * 2)有环的情况下, 求链表的入环节点
 *   fast再次从头出发,每次走一步,
 *   slow从相遇点出发,每次走一步,
 *   再次相遇即为环入口点。
 * 注:此方法在牛客BAT算法课链表的部分有讲解。
 */
//nowcoder pass
public class Solution {
     
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
         
        ListNode meetNode = meetingNode(head);
        if (meetNode == null) {//说明无环
            return null;
        }
         
        ListNode fast = head;
        ListNode slow = meetNode;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
         
        return slow;
    }
     
    //寻找相遇节点,如果无环,返回null
    public ListNode meetingNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return slow;
            }
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值