题目
![]()
python
题解:双指针
- 思路:计算两条链表的长度,找到长度差,让长的链表多走差的值,返回第一个相等的元素
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
count1,count2=0,0
pa=headA
pb=headB
while headA:# 计算链表 A 的长度
headA=headA.next
count1+=1
while headB:# 计算链表 B 的长度
headB=headB.next
count2+=1
if count1>count2:
count=count1-count2# 计算长度差
#让A链先走count步
while count!=0:
pa=pa.next
count-=1
elif count1<count2:
count=count2-count1# 计算长度差
#让B链先走count步
while count!=0:
pb=pb.next
count-=1
while pa and pb:# 同时遍历链表 A 和链表 B,找到第一个相等的节点
if pa==pb:
return pa
pa=pa.next
pb=pb.next
return None# 如果没有交点,返回 None
javascript
题解:常规
var getIntersectionNode = function(headA, headB) {
if(headA === null || headB === null) return null;
let pA = headA;
let pB = headB;
let lengthA = 0;
let lengthB = 0;
//求链表长度
while(pA.next!==null){
lengthA++;
pA = pA.next;
}
while(pB.next!==null){
lengthB++;
pB = pB.next;
}
//上一步求完长度指针在链表尾,重新放回头
pA = headA;
pB = headB;
//较长的链表先走差值
if(lengthA>lengthB){
let n = lengthA-lengthB;
while(n!=0){
pA = pA.next;
n--;
}
}else if(lengthA<lengthB){
let n = lengthB-lengthA;
while(n!=0){
pB = pB.next;
n--;
}
}
//一样长后,一起走,遇到相同返回
while(pA!==null && pB!==null){
if(pA===pB){
return pA;
}
pA=pA.next;
pB=pB.next;
}
return null;//走完都没相交
};
题解:技巧
![]()
var getIntersectionNode = function(headA, headB) {
if(headA === null || headB === null){
return null
}
let pA = headA, pB = headB
while(pA!==pB){
pA = pA === null?headB:pA.next
pB = pB ===null?headA:pB.next
}
return pA
};