文章来源地址https://www.toymoban.com/news/detail-638291.html
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
// 1、暴力解法
var getIntersectionNode = function(headA, headB) {
var p1 = new ListNode()
var p2 = new ListNode()
p1 = headA
p2 = headB
if(!p1 && !p2){
return p1
}
while(p1 != null){
while(p2 != null){
if(p2 == p1){
return p1
}else{
p2 = p2.next
}
}
p2 = headB
p1 = p1.next
}
return p1
};
function getLen(p){
var len = 0
while(p != null){
len ++
p=p.next
}
return len
}
// 2、让长的链先走多出来的几步,然后同时走
var getIntersectionNode = function(headA, headB) {
var len1 = 0
var len2 = 0
var p1 = new ListNode()
var p2 = new ListNode()
p1 = headA
p2 = headB
len1 = getLen(p1)
len2 = getLen(p2)
if(len1>len2){
for(var i = 0;i < len1-len2;i++)
p1=p1.next
}else if(len1<len2){
for(var i = 0;i < len2-len1;i++)
p2=p2.next
}
while(p1 != p2){
p1 = p1.next
p2 = p2.next
}
return p1
};
文章来源:https://www.toymoban.com/news/detail-638291.html
到了这里,关于LeetCode 热题 100 JavaScript--160. 相交链表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!