I am writing a function to find the intersection of two linked list.
My first implementation was like this (advanceByK function advances and does not return value):
public ListNode getIntersectionNode(ListNode a, ListNode b) {
int aLen=findLength(a);
int bLen = findLength(b);
if(aLen==0 || bLen==0) return null;
ListNode aTemp = a, bTemp = b;
if(aLen>bLen) {
advanceByK(aTemp,aLen-bLen);
} else if(bLen > aLen) {
advanceByK(bTemp,bLen-aLen);
}
while((aTemp!=null) && (bTemp !=null)) {
if(aTemp.equals(bTemp))return aTemp;
aTemp = aTemp.next;
bTemp = bTemp.next;
}
return null;
}
public void advanceByK(ListNode head, int k) {
while(k>0) {
if(head!=null) head=head.next;
k--;
}
}
public int findLength(ListNode head) {
ListNode temp = head;
int res =0;
if(temp==null) return res;
while(temp!=null) {
res++;
temp = temp.next;
}
return res;
}
And then I changed to this and it worked
public ListNode advanceByK(ListNode head, int k) {
while(k>0) {
if(head!=null) head=head.next;
k--;
}
return head;
}
What I am doing wrong here?
I know that Java pass by reference, and it should have moved the head in the advanceByK function