编写一个程序,找到两个单链表相交的起始节点。
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
可以换一种思路,找到相交节点的指针。如果用双指针,A指针遍历完链表A之后,遍历B链表;B指针遍历完B链表后,遍历A链表。判断条件是A指针==B指针,在两个链表长度不等的情况下,可以想象一下,必定是A指针在遍历B链表时找到相等的节点。
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode apointer = headA;
ListNode bpointer = headB;
while(apointer != bpointer){
apointer = (apointer == null ? headB : apointer.next);
bpointer = (bpointer == null ? headA : bpointer.next);
}
return apointer;
}