思路:
设A链表长度为a,B链表长度为b,两个链表的交集长度为c,那么从A链表头结点开始,走完自己一遍之后,再走B链表,走到相交结点,需要的步数为a + (b - c),同样,对于B链表,从头结点开始,走完自己一遍,再走A链表,走到相交结点,需要的步数为b + (a - c),可以发现,a + (b - c) = b + (a - c),所以,让他们同时开始走,如果有相交结点,总会相遇的,而相遇时共同指向的那个结点就是相交结点,如果没有相交结点,那他们就会把两个链表都走完,最终全是null,两种情况最后只要直接返回其中一个指针指向的结点就好了
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA;
ListNode B = headB;
while(A != B){
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}