貌似國內面試經常問得題目,以前沒遇到過。。
思路:
1: 兩個指針,一個一次走兩格,一個一次走一個。相遇了證明有環。
2: 然後因為快的那個總是比慢的那個走快一步,當他們相遇後,再走k步(k是circle的結點數量)後,他們會再相遇,從而求出circle結點數量。
3: 最後再設置兩個指針(都是一次走一步),但一開始一個比另外一個領先k步,那麼它們就會剛好在環的起點相遇。。
但是偶在初始化那裡接連犯了好幾個錯誤。
該題目的另外一個變形:“兩個鏈表,求相交的第一個節點”。
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
ListNode dCycle(ListNode head)
{
if(head == null || head.next == null)
return null;
ListNode pSlow,pFast;
pSlow = head;
pFast = head.next;
while(pFast.next != null && pFast.next.next != null && pFast != pSlow)
{
pFast = pFast.next.next;
pSlow = pSlow.next;
}
if(pFast.next == null || pFast.next.next == null)
return null;
return pFast;
}
int CycleN(ListNode cnode)
{
ListNode pFast,pSlow;
pSlow = cnode.next;
pFast = cnode.next.next;
int k = 1;
while(pFast != pSlow)
{
pFast = pFast.next.next;
pSlow = pSlow.next;
k++;
}
return k;
}
public ListNode detectCycle(ListNode head) {
if(head == null) return null;
else if(head.next == null) return null;
ListNode cNode = dCycle(head);
if(cNode == null) return null;
int iCycleN = CycleN(cNode);
ListNode pAdvNode = head;
ListNode pNode = head;
for(int i=0;i