剑指 Offer II 022. 链表中环的入口节点

使用快慢指针寻找链表中环的入口节点,快指针每次移动两步,慢指针移动一步,两者在环内相遇。然后从头结点开始的新指针与慢指针同步移动,新指针到达入口节点时,慢指针也在入口节点。
摘要由CSDN通过智能技术生成

[题目链接](剑指 Offer II 022. 链表中环的入口节点 - 力扣(LeetCode) (leetcode-cn.com))

思路

  • 1.采用快慢双指针,先找到一个环中的节点。快指针一次移动两个结点,慢指针一次移动一个结点,而该链表中存在环,所以快慢指针一定会在环中相遇。假设相遇的时候,慢指针移动了k个结点,那么快指针一定移动了2k个结点,那么k=2k-k一定是环中结点数的倍数。
  • 2.再设置一个新结点从头结点出发, 该结点和慢指针最后指向的结点同时移动。当后面的结点到达入口结点时,前面的结点比它多走k步,而k又是环中结点数的倍数,那么前面的结点也一定到达了环的入口结点。

代码

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode nodeCircle(ListNode head) {//找到环中的某个结点
        if(head == null || head.next == null) return null;
        ListNode second = head.next;
        ListNode first = second.next;
        while(first != null && second != null) {
            if(first == second) return second;
            second = second.next;
            first = first.next;

            if(first != null) first = first.next;
        }
        return null;
    }
    public ListNode detectCycle(ListNode head) {
        ListNode circle = nodeCircle(head); //找到环中的结点
        if(circle == null) return null;
        ListNode node = head; //设置一个新结点去找环的入口结点
        while(node != circle) {
            node = node.next;
            circle = circle.next;
        }
        return node;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值