/** * 根据题意,求两个链表的交点节点,如果没有交点,返回null * 由于链表存在交点,所以,从交点开始直到末尾,都是相同的节点 * 鉴于以上的原因,可以求出A、B链表的长度差N,长的链表先走N步,再 A、B一起走,直到遇到相同的节点 */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode a = headA; ListNode b = headB; //求A的长度 int lenA = 0; int lenB = 0; while (a != null) { a = a.next; lenA++; } //求B的长度 while (b != null) { b = b.next; lenB++; } //还原A,B链表 a = headA; b = headB; //A、B交换,确保 A链表是最长的 if (lenA < lenB) { int temp = lenA; lenA = lenB; lenB = temp; ListNode node = a; a = b; b = node; } int n = lenA - lenB; while (n-- > 0) { a = a.next; } while (a != null) { if (a == b) { return a; } a = a.next; b = b.next; } return null; }
/** * 双指针计算 * 解析:https://leetcode.cn/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode-solutio-a8jn/ */ public ListNode getIntersectionNode2(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode pA = headA, pB = headB; while (pA != pB) { pA = pA == null ? headB : pA.next; pB = pB == null ? headA : pB.next; } return pA; }