热门搜索 :
考研考公
您的当前位置:首页正文

【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;
        
        
    }
}
Top