Leetcode: linked-list-cycle-ii

本文介绍了一种高效检测链表中是否存在环的方法,并给出了具体的实现步骤和代码示例。通过使用快慢指针技术,可以在不消耗额外空间的情况下找到环的起始节点。

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

题目:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?


分析:

给定一个链表,返回这个链表中环的开始,若无环,那么返回null,并且不能有额外的空间。首先需要判断是否有环,定义两个指针slow和fast,slow每次前进一格,fast每次前进

两格,如果有环,那么这两个指针必然会相遇;如果没有环,那么直接返回null即可;在有环的情况下,将slow指针指向相遇节点,将fast指针指向开始节点,继续前进,这时两个

指针每次前进一格,当指针再次相遇的时候,就是环开始的位置。


具体代码如下:


/**
 * 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 meeting = meetingNode(head);
        
        if (meeting == null)
            return null;
        
        ListNode fast = head;
        ListNode slow = meeting;
        
        while(slow != fast){
            fast = fast.next;
            slow = slow.next;
        }
        
        
        return fast;
    }
    
    public ListNode meetingNode(ListNode head){
        
        if(head == null || head.next == null)
            return null;
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast.next != null && fast.next.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、付费专栏及课程。

余额充值