0

The following code is supposed to increment the head pointer to the next node in linked list. However, it doesn't do so. But the value of head data is being changed.

The changeHead(Node head) method is changing the head of the linked list as the next node of the linked list.

Could anybody please help me out why only data value is getting changed but head pointer of the linked list is not getting changed ?

class Node
{
int data;
Node next;
Node(int data)
  {
   this.data=data;
   this.next=null;
  }
}

class LinkedList
{
 Node head;

 public LinkedList() //constructor for LinkedList class
 {
  this.head=null;  
 }

 void insert(int data)
 {
  Node s=new Node(data);
  if(head==null)
  {
    head=s;
  }
  else
  {
   Node t=head;
   while(t.next!=null)
       t=t.next;
   t.next=s;
  }
}
}

class Main
{
    public static void main(String[] args) 
    {
       LinkedList ll=new LinkedList();
       ll.insert(1);
       ll.insert(2);
       ll.insert(3);
       ll.insert(4);
       printList(ll.head); //calling method to print the list
       changeHead(ll.head); //changing the head to the next node
       printList(ll.head); //calling method to print the changed list

    }
   static void printList(Node head)
    {
       Node t=head;
       while(t!=null)
       {
            System.out.print(t.data+" ");
            t=t.next;
       }
       System.out.println();
    }
     static void changeHead(Node head) 
     {
      head=head.next;
     }

  }


Output:
1 2 3 4 
1 2 3 4

Expected output:
1 2 3 4
2 3 4

/*However if I change the function changeHead(Node head) as */
static void changeHead(Node head)
 {
  head.data=444;
 }  
then the output is as per expectations i.e. 
1 2 3 4
444 2 3 4
kk.
  • 3,747
  • 12
  • 36
  • 67
KTDLIN
  • 21
  • 3
  • 3
    Objects in Java aren't passed by reference. References are passed by value. See https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1 – Jon Skeet Jun 19 '19 at 11:14
  • 1
    As an aside, for further questions, your code would be easier to read if you'd apply consistent indentation to everything. On the other hand, thanks for including a complete example. – Jon Skeet Jun 19 '19 at 11:15

1 Answers1

0

Since the reference head is passed in by value and you change that value (you change where the reference points to) the caller does not see any change.

If you use the reference of head to change some of the contents head points to then that change is visible to everyone.

luk2302
  • 55,258
  • 23
  • 97
  • 137