快慢指针 02
LeetCode 142
https://leetcode-cn.com/problems/linked-list-cycle-ii/
题解
/**
* 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) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// 有环,开始找环的入口
if (slow == fast) {
while (slow != head) {
head = head.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}
网友评论