The main nodes of linked lists are not updated


I have been implementing a simple utility function in Linked lists called MoveNode() using Java.

The main aim of MoveNode() is to remove the first node of one linked list (Source list) and add it to the beginning of another Linked list (Destination list).

Example is as follows:

Destination_Linked_List = {1,2,3}
Source_List_List = {4,5,6}

After calling MoveNode(Destination_Linked_List,Source_List_List) we get:

Destination_Linked_List = {4,1,2,3}
Source_List_List = {5,6}

The following is my Java implementation of the above:

static void MoveNode(LinkedList LL1,LinkedList LL2)
    Node sourceref = LL2.head;
    Node destref = LL1.head;
    Node temp =; = destref;
    LL1.head = sourceref;
    LL2.head = temp;

Works Perfectly!!

But if I change the last two lines of my code and replace it with the local Node variables, the output changes completely.

Here it is:

If I change:

   LL1.head = sourceref;
   LL2.head = temp;


   destref = sourceref;
   sourceref = temp;

The output which I get by performing this change is:

 Destination_Linked_List = {1,2,3}
 Source_List_List = {4,1,2,3}

What is the reason behind this anomaly? Why do the head nodes of the lists not get updated properly? What am I missing?

P.S. - The head node is a global variable which can be accessed from any function.

Why does the head nodes of the lists does not get updated properly?

Because you're just changing the values of local variables. That's all you're doing - you're not making any changes to the list objects at all. Changes to local variables have no effect outside the method itself.

Note that when I say "changes to local variables" I mean something like:

localVariable = someOtherValue;

If instead you have:

localVariable.someMember = someOtherValue;

then that might have an effect outside the method, because that's changing the member of an object. If that object is accessible outside the method, then the change will be visible there too.