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