编写一个程序,找到两个单链表相交的起始节点。
双指针
错的人迟早会走散,而对的人迟早会相逢!
指针1从A向后走,到末尾时指针1移到B
指针2从B向后走,到末尾时指针2移到A
两个人都要走A+B的长度 若两个人在走完A+B距离之前相遇
此节点为相交节点 否则两个人会在走完A+B的null处结束
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
ListNode head1, head2;
head1 = headA;
head2 = headB;
while(head1 != head2){
if(head1 != null){
head1 = head1.next;
}
else{
head1 = headB;
}
if(head2 != null){
head2 = head2.next;
}
else{
head2 = headA;
}
}
return head1;
}
}