给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
图示两个链表在节点 c1 开始相交:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:后面长度相同的位置,齐头并进,找公共的节点
/** * 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) { int lenA = 0, lenB = 0; ListNode pA = headA, pB = headB; while(pA != null) { pA = pA.next; lenA++; } while(pB != null) { pB = pB.next; lenB++; } if(lenA > lenB) { lenA ^= lenB; lenB ^= lenA; lenA ^= lenB; ListNode temp = headB; headB = headA; headA = temp; } int len = lenB - lenA; ListNode indexB = headB; while(len > 0) { indexB = indexB.next; len--; } ListNode indexA = headA; while(indexA != indexB) { indexA = indexA.next; indexB = indexB.next; } return indexB; } }