其他分享
首页 > 其他分享> > 面试题 02.07. 链表相交

面试题 02.07. 链表相交

作者:互联网

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

        ListNode h1 = headA;
        ListNode h2 = headB;

        /**
         * 两个长度不同的链表,如果同步遍历,肯定不能同时遍历到终点
         * 可以让A链表遍历完以后继续遍历B,B链表遍历完以后继续遍历A,这样遍历的总长度就是一样了
         */
        while (h1 != h2){

            h1 = h1 == null ? headB : h1.next;
            h2 = h2 == null ? headA : h2.next;
        }

        return h1;
    }
}

/**
 * 时间复杂度 O(m + n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/

标签:面试题,遍历,ListNode,h2,02.07,h1,链表,headB
来源: https://www.cnblogs.com/taoyuann/p/15907903.html