I have node class as
class Node{
int data;
Node next;
}
I have to insert nodes to the list. It works properly. But always the head value is zero.
public void createlist(Node n,int p)
{
Node newone = new Node();
newone.data=p;
newone.next=null;
if(n==null)
n=newone;
else
{
while(temp.next!=null)
temp=temp.next;
temp.next=newone;
}
}
In main function I have created head node as
public static void main(String args[] ) {
Scanner s = new Scanner(System.in);
Node head=new Node();
createlist(head,5);
}
after creating this implementation the list starting from head looks like 0->5. Why did the 0 come?.
Zero comes from the
headnode itself:It is never modified by
createListmethod, so the default value of zero remains in thedatafield.It boils down to inability to change
headinsidemainby assigningnin the code below:That is why you are forced to create
new Nodeinsidemain, so in factnis nevernull.You can fix this problem in several ways:
headnode in for printing, deletions, etc., orNodeobjects to return the modified list - this would let you insert new nodes or delete the head node, orMyListclass that owns all nodes - move all list operations on the "umbrella" class, and deal with theheadnode there.