Aryak Sengupta
Aryak Sengupta

Reputation: 1819

Head nodes of Linked lists not getting 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 = sourceref.next;
    sourceref.next = 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;

to:

   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.

Upvotes: 0

Views: 273

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500535

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.

Upvotes: 3

Eran
Eran

Reputation: 393831

Well, if you don't change the head of the source list, is still points to the same first element, but that first element already points to the start of the destination list.

Therefore the destination list looks unchanged (since you didn't change its head) and the source list begins with the same head, but continues with the elements of the destination list.

LL1.head -> 1->2->3

            ^
            | 
LL2.head -> 4 5->6

Upvotes: 1

Related Questions