public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) {
return null;
}
ListNode curA = headA,curB = headB;
boolean find = false;
int countA = 0,countB = 0;
while(curA != null || curB != null) {
if(curA != null) {
countA++;
curA = curA.next;
}
if(curB != null) {
countB++;
curB = curB.next;
}
}
int i = 0, li = Math.abs(countA - countB);
ListNode shead = headA, lhead = headB, tmp = null,cur = null;
if(countA > countB) {
tmp = shead;
shead = lhead;
lhead = tmp;
}
if(countA != countB) {
cur = lhead;
while(i < li) {
cur = cur.next;
i++;
}
lhead = cur;
}
while(shead != null && lhead != null) {
if(shead == lhead) {
find = true;
break;
}
shead = shead.next;
lhead = lhead.next;
}
return find ?lhead:null;
}
160. Intersection of Two Linked Lists
最新推荐文章于 2024-07-09 23:43:07 发布