# 判断一个单链表是否有环，如果有，找出环的起始位置 [No. 36]

How can one determine whether a singly linked list has a cycle?

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.

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

2016-09-01 09:18:10

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

2012-05-26 09:41:15

#### 判断单链表中是否有环，如果有环则找到环的入口地址

2014-11-04 21:15:29

#### 判断单链表中是否有环，找到环的入口节点

2017-01-04 21:10:42

#### 判断单链表是否有环，如果有找出环的入口位置=>求两个相交链表的交点

2012-04-26 21:57:19

#### 判断单链表是否有环，以及如何找起始点，环的长度

2014-10-03 21:15:59

#### 首先如何判断一个链表是否有环，并找出环的入口

2015-04-08 15:49:54

#### 判断单向链表中是否有环和查找环的入口

2015-08-01 13:24:30

#### 判断一个单链表是否有环，若有环，求进入环中的第一个节点

2017-07-19 17:23:08

#### 判断一个单链表是否有环，若有，找出环的入口节点

2016-06-19 14:59:15