/**
* 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(hasCycle(head) == null){
return null;
}else{
//相交节点
ListNode node = hasCycle(head);
//从头节点出发到相遇
ListNode pre = head;
while(pre != node){
pre = pre.next;
node = node.next;
}
return pre;
}
}
//判断有无环
public ListNode hasCycle(ListNode head){
if(head == null || head.next == null){
return null;
}
ListNode slow = head;
ListNode fast = head;
while(fast!=null && slow != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return slow;
}
}
return null;
}
}
两个链表相交的一系列问题可以参考另外一篇博客:2022.3.20 算法打卡。_失忆机器的博客-CSDN博客