添加面试题 02.07. 链表相交 javaScript版本

This commit is contained in:
qingyi.liu
2021-05-21 14:25:55 +08:00
parent 202e201919
commit 2aed976e46

View File

@ -155,6 +155,42 @@ Python
Go
javaScript:
```js
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getListLen = function(head) {
let len = 0, cur = head;
while(cur) {
len++;
cur = cur.next;
}
return len;
}
var getIntersectionNode = function(headA, headB) {
let curA = headA,curB = headB,
lenA = getListLen(headA),
lenB = getListLen(headB);
if(lenA < lenB) {
[curA, curB] = [curB, curA];
[lenA, lenB] = [lenB, lenA];
}
let i = lenA - lenB;
while(i-- > 0) {
curA = curA.next
}
while(curA && curA !== curB) {
curA = curA.next;
curB = curB.next;
}
return curA;
};
```