public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {ListNode ap=headA;ListNode bp=headB;int lenA=0,lenB=0;//求两个链表长度while(ap!=null){ap=ap.next;lenA++;}while(bp!=null){bp=bp.next;lenB++;}ap=headA;bp=headB;int len=0;//用来计算让两个链表长度相同后的长度//让两个链表长度相同if(lenA<lenB){len=lenA;for(int i=0;i<lenB-lenA;i++){bp=bp.next;}}else{len=lenB;for(int i=0;i<lenA-lenB;i++){ap=ap.next;}}int count=0;for(int i=0;i<len;i++){if(ap==bp){return ap;}else{ap=ap.next;bp=bp.next;}count++;}return null;}
}
class Solution(object):def getIntersectionNode(self, headA, headB):ap=headAbp=headBlenA=0lenB=0len=0count=0while ap:ap=ap.nextlenA+=1while bp:bp=bp.nextlenB+=1ap=headAbp=headBif lenA<lenB:len=lenAfor i in range(lenB-lenA):bp=bp.nextelse:len=lenBfor i in range(lenA-lenB):ap=ap.nextfor i in range(len):if ap==bp:return apelse:ap=ap.nextbp=bp.nextcount+=1return None
其它方法:
代码随想录 (programmercarl.com)