160. 相交链表-leetcode hot100

78 阅读1分钟

image.png

方法:双指针

image.png

headA和headB的长度分别为m,n。使用双指针同步遍历

public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

    //其中一个链表为空则返回空
    if (headA == null || headB == null) return null;
    ListNode pA = headA, pB = headB;
    //双指针遍历,当m!=n则遍历完还没相交,则在遍历另一个链表,当两个链表遍历m+n后都为空
    while (pA != pB) {
        pA = pA == null ? headB : pA.next;
        pB = pB == null ? headA : pB.next;
    }
    return pA;
}
}