142. Linked List Cycle II

本文介绍了一种链表环检测算法,通过快慢指针判断链表是否存在环,并计算环内节点数量。随后,利用特定策略定位环的起始节点,提供了完整的代码实现。

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

 

[3,2,0,-4]
1

Expect:tail connects to node index 1

Actually:tail connects to node index 3

思路是判断有环否。

然后计算环中节点数(长度)n

然后fast,slow从头开始,slow每次移动一个节点。fast每次移动n个节点。当它们再次相遇,同时指向的节点为环的第一个节点。

/**
 * 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) {
        int count = 1, isCycle = 0;
        ListNode s = head, f = head;
        
        if (head == null || head.next == null) {
            return null;
        }
        
        while (f.next.next != null && s.next != null) {
            f = f.next.next;
            s = s.next;
            if (f == s) {
                isCycle = 1;
                break;
            }
        }   //if linked list is Cycle linked list, isCycle is 1           
        
        if (isCycle == 1) { //Cycle linked list
            f = f.next;
            while (f != s) {
                count++;
                f = f.next;
            } // get the length of cycle

            
            ListNode s1 = head;
            ListNode f1 = head;
            
            for (int i = 0;i < count; i++) {
                f1 = f1.next;
            }
            
            while (f1 != s1) {
              
                s1 = s1.next;
                for (int i = 0;i < count; i++) {
                    f1 = f1.next;
                }
            }
            return s1;           
        }
        return null;
    } 
           
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值