[题目链接](剑指 Offer II 022. 链表中环的入口节点 - 力扣(LeetCode) (leetcode-cn.com))
思路
- 1.采用快慢双指针,先找到一个环中的节点。快指针一次移动两个结点,慢指针一次移动一个结点,而该链表中存在环,所以快慢指针一定会在环中相遇。假设相遇的时候,慢指针移动了k个结点,那么快指针一定移动了2k个结点,那么k=2k-k一定是环中结点数的倍数。
- 2.再设置一个新结点从头结点出发, 该结点和慢指针最后指向的结点同时移动。当后面的结点到达入口结点时,前面的结点比它多走k步,而k又是环中结点数的倍数,那么前面的结点也一定到达了环的入口结点。
代码
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode nodeCircle(ListNode head) {//找到环中的某个结点
if(head == null || head.next == null) return null;
ListNode second = head.next;
ListNode first = second.next;
while(first != null && second != null) {
if(first == second) return second;
second = second.next;
first = first.next;
if(first != null) first = first.next;
}
return null;
}
public ListNode detectCycle(ListNode head) {
ListNode circle = nodeCircle(head); //找到环中的结点
if(circle == null) return null;
ListNode node = head; //设置一个新结点去找环的入口结点
while(node != circle) {
node = node.next;
circle = circle.next;
}
return node;
}
}