-1

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

Zakk
  • 758
  • 3
  • 11
  • 20

1 Answers1

1

In your first implementation, head is a reference to a specific ListNode object. If you were to make modifications to head by calling methods on it, it would behave in the way you would expect for something being passed by reference.

However, what you did instead was this:

head=head.next;

That doesn't modify any state in the object referenced by head. Instead, it changes which ListNode the local head variable is pointing to. The original ListNode pointed to by head is left unchanged.

Jordan
  • 2,273
  • 9
  • 16