题目需要找到链表中环的第一个节点,设置快慢指针遍历该链表,当快慢指针相遇说明有环,然后再遍历一次,找入口节点。
/**
* 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;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // 相遇,说明有环
break;
}
}
if (fast == null || fast.next == null) {
return null;
}
slow = head;
while (slow != fast) { // 找环的起点
slow = slow.next;
fast = fast.next;
}
return slow;
}
} 
京公网安备 11010502036488号