55.鏈表中環的入口結點
阿新 • • 發佈:2019-01-15
bject 輸出 while his itl span return scribe fas
題目描述
給一個鏈表,若其中包含環,請找出該鏈表的環的入口結點,否則,輸出null。題目解答
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ public class Solution { public ListNode EntryNodeOfLoop(ListNode pHead){ if(pHead==null || pHead.next==null){return null; } ListNode pFast=pHead; ListNode pSlow=pHead; while(pFast!=null && pFast.next!=null) { pSlow = pSlow.next; pFast = pFast.next.next; if(pSlow==pFast){ pFast=pHead; while(pFast!=pSlow){ pFast=pFast.next; pSlow=pSlow.next; } if(pFast==pSlow){ return pSlow; } } } return null; } }
快慢指針
55.鏈表中環的入口結點