因为开始学习前端所以开始用js练习算法。
刚开始可能不太熟悉所以代码打起来很臭。
凑合着看看也行。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var reverseList = function(head){
let last = null;
let cur = head;
let node;
while(cur.next != null){
node = cur;
cur = cur.next;
node.next = last;
last = node;
}
return last;
}
var listLength = function(head){
let res = 0;
while(head){
res++;
head = head.next;
}
return res;
}
var getIntersectionNode = function(headA, headB) {
let reA = headA, reB = headB;
let lenA = listLength(reA), lenB = listLength(reB);
let res = null;
if(lenA < lenB){
let t = reA;
reA = reB; reB = t;
t = lenA;
lenA = lenB; lenB = t;
}
let len = lenA - lenB;
while(len--){
reA = reA.next;
}
for(let i = 0; i < lenB; i++){
if(reA == reB){
res = reA;
break;
}
reA = reA.next;
reB = reB.next;
}
return res;
};
总体思路就是把长的削平,然后再进行链表的比较。
注意:值(value)相同不代表是相交的链表,一定是地址相同才是相交的。