算法思想
先分析是否有環
static bool JudgeCircleExists(Link head)
{
Link first = head; //
Link second = head; //
while (second
{
second = second
first = first
if (second == first)
return true;
}
return false;
}
那又如何知道環的長度呢?
根據上面的算法
static int GetCircleLength(Link point)
{
int length =
Link curr = point;
while (curr
{
length++;
curr = curr
}
return length;
}
繼續我們的討論
延續上面的思路
static int GetLengthFromHeadToPoint(Link head
{
int length =
Link curr = head;
while (curr != point)
{
length++;
curr = curr
}
return length;
}
如果我們把環從P點
一個單鏈表是從P點出發
我們可以參考第
private static Link FindIntersect(Link head)
{
Link p = null;
//get the point in the circle
bool result = JudgeCircleExists(head
if (!result) return null;
Link curr
Link curr
//length from head to p
int M =
while (curr
{
M++;
curr
}
//circle length
int N =
while (curr
{
N++;
curr
}
//recover curr
curr
curr
//make
if (M > N)
{
for (int i =
curr
}
else if (M < N)
{
for (int i = 0; i < N – M; i++)
curr2 = curr2.Next;
}
//goto the intersect
while (curr1 != p)
{
if (curr1 == curr2)
{
return curr1;
}
curr1 = curr1.Next;
curr2 = curr2.Next;
}
return null;
}
From:http://tw.wingwit.com/Article/program/sjjg/201405/30932.html