Description
https://leetcode.com/problems/linked-list-cycle-ii/
题目大意:找到单向链表中环的入口结点
Solving Ideas
- 使用快慢两个指针判断链表是否含有环
- 如果有环,则统计环中的结点数目
- 接着使指针p2从头开始,先走结点数目的步数,然后p1从头开始与p2一起前进直至p1==p2
更详细的说明请移步链表中环的入口结点
Solution
class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode p1 = head, p2 = head.next;
//1.Determine if a linked list contains a ring
while (p2 != null && p1 != p2) {
p1 = p1.next;
p2 = p2.next;
if (p2 != null) {
p2 = p2.next;
}
}
if (p1 != p2) {
return null;
}
//2.Calculate the number of nodes in the ring
int count = 1;
while (p2.next != p1) {
p2 = p2.next;
count++;
}
//3.Find the entry node of the ring
p1 = head;
p2 = head;
for (int i = 0; i < count; i++) {
//let p2 move forward "count" steps
p2 = p2.next;
}
while (p1 != p2) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}