public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int sizeA = 0;
int sizeB = 0;
while(curA != null){
sizeA++;
curA = curA.next;
}
while(curB != null){
sizeB++;
curB = curB.next;
}
if(sizeA > sizeB){
int len = sizeA - sizeB;
ListNode tempA = headA;
ListNode tempB = headB;
for(int i = 0; i < len ; i++){
tempA = tempA.next;
}
while(tempA != tempB){
tempA =tempA.next;
tempB = tempB.next;
}
return tempA;
}else {
int len = sizeB - sizeA;
ListNode tempA = headA;
ListNode tempB = headB;
for(int i = 0; i < len ; i++){
tempB = tempB.next;
}
while(tempA != tempB){
tempA = tempA.next;
tempB = tempB.next;
}
return tempA;
}
}
}
代码随想录算法训练营第四天 面试题 02.07. 链表相交
最新推荐文章于 2024-06-13 14:43:16 发布