题目描述
LeetCode 题目链接:环形链表 II
题解
- 快慢指针经典玩法-又称龟兔赛跑方法,Floyd提出的。
版本一
- 分别循环两次得出结果
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode p = head;
ListNode fastPoint = p.next;
while ((fastPoint != null && fastPoint.next != null) && p != fastPoint) {
fastPoint = fastPoint.next.next;
p = p.next;
}
if ((p == fastPoint)) {
p = head;
fastPoint = fastPoint.next; // 关键
while (p != fastPoint) {
p = p.next;
fastPoint = fastPoint.next;
}
return fastPoint;
} else
return null;
}
}
版本二
- 与版本一本质无区别
public class Solution {
public ListNode detectCycle(ListNode p) {
if (p == null || p.next == null) return null;
ListNode turtle = p;
ListNode rabbit = p;
while (rabbit != null && rabbit.next != null) {
turtle = turtle.next;
rabbit = rabbit.next.next;
if (turtle == rabbit) {
turtle = p;
while (turtle != rabbit ){
turtle = turtle.next;
rabbit = rabbit.next;
}
return turtle;
}
}
return null;
}
}
版本三
- set 集合判重
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode point = head;
Set<ListNode> markedNodes = new HashSet<ListNode>();
for (point = head; point != null && markedNodes.add(point); point = point.next);
return point;
}
}