题目信息:(链表判断是否有环,并且找到环入口节点)
* levev = medium * id = 142 * * Given a linked list, return the node where the cycle begins. If there is no cycle, return null. * * To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in * the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. * * Note: Do not modify the linked list.
解法1:使用辅助 set 集合
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slowNode = head;
Set<ListNode> set = new HashSet<>();
while (slowNode.next != null) {
if (set.contains(slowNode)) {
return slowNode;
}
set.add(slowNode);
slowNode = slowNode.next;
}
return null;
}
解法2:快慢指针(固定2倍速度)
public ListNode detectCycle2(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slowNode = head;
ListNode fastNode = head;
while (fastNode != null && fastNode.next != null) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
if (slowNode == fastNode) {
fastNode = head;
while (slowNode != fastNode) {
slowNode = slowNode.next;
fastNode = fastNode.next;
}
return slowNode;
}
}
return null;
}
快慢指针的关键思路: