输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
/**
* 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 meetNode = meetingNode(head);
if (meetNode == null) {//说明无环
return null;
}
ListNode fast = head;
ListNode slow = meetNode;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
//寻找相遇节点,如果无环,返回null
public ListNode meetingNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return slow;
}
}
return null;
}
}
来源:CSDN
作者:zhaihm_
链接:https://blog.csdn.net/zhaihm_/article/details/104755835