链表--相交链表(leetcode 160

题解

若相交,链表A: a+c, 链表B : b+c. a+c+b = b+c+a 。则会在公共处c起点相遇。若不相交,a +b = b+a 。因此相遇处是NULL

用一句歌词总结:走过你来时的路

代码:

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if (headA == null || headB == null){
        return null;
    }
    ListNode tempA = headA;
    ListNode tempB = headB;
    while (tempA != tempB){
        tempA = tempA == null ? headB : tempA.next;
        tempB = tempB == null ? headA : tempB.next;
    }

    return tempB;
}

时间:O(n),空间:O(1)


引申

《程序员代码面试指南》P62 “两个单链表相交的一系列问题”

猜你喜欢

转载自www.cnblogs.com/swifthao/p/13174390.html