链表相交
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
。
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
//定义一个求链表长度的函数
var getListlen = function(head){
let cur = head;
let len = 0;
while(cur){
len++;
cur = cur.next;
}
return len;
}
var getIntersectionNode = function(headA, headB) {
let curA = headA,curB = headB;
//求出两个链表的长度
let lenA = getListlen(headA);
let lenB = getListlen(headB);
//令A链表为长度更长的链表
if(lenA<lenB){
[curA,curB] = [curB,curA];
[lenA,lenB] = [lenB,lenA];
}
let i = lenA - lenB;
while(i>0){
curA = curA.next;
i--;
}
//当curA = null或者两链表有相同点时停止(该点为两链表的相交点)
while(curA&&curA!==curB){
curA = curA.next;
curB = curB.next;
}
return curA
};