您好,欢迎来到花图问答。
搜索
您的当前位置:首页【1错1对0】链表环入口 Linked List Cycle I

【1错1对0】链表环入口 Linked List Cycle I

来源:花图问答
日期 是否一次通过 comment
2019-02-09 20:20 N 知道方法,但是实现太鸡毛
2019-02-10 12:20 Y 真的很easy

题目:判断单链表是否有环,并输出环入口
思路:

  1. 快慢指针是否相遇判断有环与否;
  2. 两指针同速,分别从起点和相遇点开始遍历,再次相遇的点即为环入口

public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if(pHead == null || pHead.next == null) {
            return null;
        }
        
        ListNode pSlow = pHead;
        ListNode pFast = pHead;
        
        while(pFast != null && pFast.next != null) {
            pSlow = pSlow.next;
            pFast = pFast.next.next;
            
            if(pSlow == pFast) {
                pSlow = pHead;
                while(pSlow != pFast) {
                    pSlow = pSlow.next;
                    pFast = pFast.next;
                }
                return pSlow;
            }
        }
        return null;
        
        
    }
}

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务