1. 定义
快慢指针:是在同一个数组中使用的两个指针,它们以不同的速度移动。
2. 题目
3. 思路和题解
这道题也是一道很经典的用双指针的题目,但是和我们之前的双指针有所不同,这道题需要使用的是快慢指针,两个指针需要以不同的速度向前。速度慢的指针每次移动一个位置,速度快的指针每次移动两个位置,如果这两个指针可以相遇的话,那就说明原链表中存在着环,因为如果没有环的话,速度不同的两个指针是永远也不会遇到的。
此外题目还需要输出链表开始入环的第一个节点,因此这个时候还需要一个指针。当之前的快慢指针第一次遇到之后,将这个指针指向链表头部,然后和慢指针继续一起向前走,这个指针和慢指针最终会在入环的第一个节点相遇。
代码如下:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head, fast = head;
while (fast != null) {
slow = slow.next;
if (fast.next != null) {
fast = fast.next.next;
} else {
return null;
}
if (fast == slow) {
ListNode ptr = head;
while (ptr != slow) {
ptr = ptr.next;
slow = slow.next;
}
return ptr;
}
}
return null;
}
}