不多说,上代码,一看就懂。主要思路就是 从链表尾往链表头看
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int countA=getCount(headA);
int countB=getCount(headB);
int gap=Math.abs(countA-countB);
if (countA>countB){
while (gap>0){
headA=headA.next;
gap--;
}
}else{
while (gap>0){
headB=headB.next;
gap--;
}
}
return getResult(headA,headB);
}
public int getCount(ListNode node){
int count=0;
while (node!=null){
count++;
node=node.next;
}
return count;
}
public ListNode getResult(ListNode nodeA,ListNode nodeB){
while (nodeA!=null){
if (nodeA==nodeB){
return nodeA;
}
nodeA=nodeA.next;
nodeB=nodeB.next;
}
return null;
}
}