判断一个单链表是否有环，如果有，找出环的起始位置

public boolean hasLoop(Node head) {
if (head == null) return false;
//slow pointer
if (sPointer == null) return false;
//fast pointer
Node fPointer = sPointer.next;
while (sPointer != null && fPointer != null) {
if (sPointer == fPointer) return true;
sPointer = sPointer.next;
fPointer = fPointer.next;
if (fPointer != null) {
fPointer = fPointer.next;
}
}
return false;
}
/* (Step 1) Find the meeting point. This algorithm moves two pointers at
* different speeds: one moves forward by 1 node, the other by 2. They
* must meet (why? Think about two cars driving on a track—the faster car
* will always pass the slower one!). If the loop starts k nodes after the
* start of the list, they will meet at k nodes from the start of the
* loop. */
while (TRUE) {
n1 = n1->next;
n2 = n2->next->next;
if (n1 == n2) {
break;
}
}
// Find the start of the loop.
while (n1 != n2) {
n1 = n1->next;
n2 = n2->next;
}
Now n2 points to the start of the loop.

• 本文已收录于以下专栏：

举报原因： 您举报文章：判断一个单链表是否有环，如果有，找出环的起始位置 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)