0
点赞
收藏
分享

微信扫一扫

LeetCode 142. 环形链表 II

在这里插入图片描述
原题链接

实现过程如下(动图来源代码随想录)

  1. 首先寻找快慢指针相遇的地方
  2. 然后让慢指针固定此处,快指针指向了head
  3. 然后while(fast != slow)的时候,不停地移动两个指针,直到相遇
  4. 返回slow或者fast都可以
  5. 二刷:一开始的时候,一定要判断 fast == null || fast.next == null 的情况,否则会报空指针异常
    在这里插入图片描述
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(true){
        //在此位置要判断当前结点和后一个结点是否有null
            if(fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) break;
        }
        fast = head;
        while(fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
举报

相关推荐

0 条评论