思路
两条链表长短不一,找公共交点必须先对齐。记录两个链表各自长度,长的向短的看齐,长的先走多出来的那么一截,之后两者一起走,直到相遇或抵达末尾
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int a=0,b=0;
ListNode temp=headA;
while(temp!=null){
++a;
temp=temp.next;
}
temp=headB;
while(temp!=null){
++b;
temp=temp.next;
}
if(a>b){
temp=headA;
for(int i=0;i<a-b;++i){
temp=temp.next;
}
ListNode t=headB;
while(t!=temp){
t=t.next;
temp=temp.next;
}
}else{
temp=headB;
for(int i=0;i<b-a;++i){
temp=temp.next;
}
ListNode t=headA;
while(t!=temp){
t=t.next;
temp=temp.next;
}
}
return temp;
}
}