[劍指offer]找到連結串列環的入口節點java
阿新 • • 發佈:2019-01-23
//基於hash索引 public ListNode EntryNodeOfLoop1(ListNode pHead) { ListNode next = pHead; Set<ListNode> set = new HashSet<ListNode>(); ListNode result = null;//可能不存在環 while(next!=null){ if(!set.contains(next)){ set.add(next); next = next.next; }else{ result = next; break; } } return result; } //基於快慢指標 public static ListNode EntryNodeOfLoop2(ListNode pHead){ //找到環的大小 int m= 0; ListNode next = pHead.next; ListNode fast =pHead; ListNode low = pHead; while(next!=null&&next.next!=null){ low = low.next; fast =next.next; next = fast.next; m++; if(low == fast) break; } if(next==null||next.next==null)//說明沒有環 return null; //找到連結串列中倒數第m個節點 //快指標先走m步 fast = pHead; low = pHead; for(int i = 0 ;i<m; i++){ fast = fast.next; } while(fast != low){ fast = fast.next; low = low.next; } return fast; }