双指针:遍历两次
a+重+b=b+重+a
/**
* 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) {
if(headA==null||headB==null){
return null;
}
ListNode a=headA,b=headB;
while(a!=b){
a = a== null? headB: a.next;
b = b== null? headA: b.next;
}
return a;
}
}
遍历一次
/**
* 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 lena=0,lenb=0,dif=0;
ListNode a=headA,b=headB;
while(a!=null){
lena++;
a=a.next;
}
while(b!=null){
lenb++;
b=b.next;
}
if(lena<lenb){
a=headB;
b=headA;
dif=lenb-lena;
}else{
a=headA;
b=headB;
dif=lena-lenb;
}
for(int i=0;i<dif;i++){
a=a.next;
}
while(a!=null&&b!=null){
if(a==b){
return a;
}
a=a.next;
b=b.next;
}
return null;
}
}