编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
刚开始想到的是暴力解法,双层循环遍历两个链表,然后对比是否有相同节点,有的话就直接返回,结果翻车了
var getIntersectionNode = function(headA, headB) {
var startB = headB
if(!headA || !headB){
return null
}
while(headA){
console.log('A'+headA.val);
while (headB) {
console.log('B'+headB.val);
if(headB.val == headA.val) {
return headB.val
}
headB = headB.next
}
if(headA.val == headB.val){
return headA.val
}
headB = startB
headA = headA.next
}
return null
};
判断到4就结束 了,好吧,行不通。
第二种方法:
var getIntersectionNode = function(headA, headB) {
if (!headA || !headB) {
return null;
}
let a = headA,
b = headB;
// 相交则返回当前节点,否则返回 null
// 当 a、b 还没相交时:
// 1. 如果 a 为 null,将 headB 赋值给 a;
// 2. 如果 b 为 null,将 headA 赋值给 b;
while (a !== b) {
a = a ? a.next : headB;
b = b ? b.next : headA;
console.log('a:'+JSON.stringify(a))
console.log('b:' + JSON.stringify(b));
}
return a;
};
因为两个链表的长度不一样,但是两个链表分别加上对方的链表长度就一样了,如下:
这样的话,如果链表有相交部分,那么在遍历的时候一定会相等的,等到链表相等的时候就退出循环返回相等部分的值。可能不理解怎么就相等了,原因是链表next指针在向后移动的时候,前面没有指针指向的部分会被删除掉,这样就只比较剩下的部分,直到两个相等了退出循环。若是不等,也会输出null,不会造成死循环
执行步骤如下:
a:{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}
b:{"val":0,"next":{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}}
a:{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}
b:{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}
a:{"val":4,"next":{"val":5,"next":null}}
b:{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}
a:{"val":5,"next":null}
b:{"val":4,"next":{"val":5,"next":null}}
a:null
b:{"val":5,"next":null}
a:{"val":5,"next":{"val":0,"next":{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}}}
b:null
a:{"val":0,"next":{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}}
b:{"val":4,"next":{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}}
a:{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}
b:{"val":1,"next":{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}}
a:{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}
b:{"val":8,"next":{"val":4,"next":{"val":5,"next":null}}}