1. 题目
题目链接142. 环形链表 II
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) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
break;
}
}
if (fast == null || fast.next == null) return null;
slow = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
本文介绍了一种解决LeetCode上142题“环形链表II”的高效算法。通过使用快慢指针技巧,可以准确地找到链表中环的起始节点。文章提供了详细的实现思路和完整的Java代码示例。
276





