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 head
node itself:
Node head=new Node();
It is never modified by createList
method, so the default value of zero remains in the data
field.
It boils down to inability to change head
inside main
by assigning n
in the code below:
if(n==null)
n=newone;
That is why you are forced to create new Node
inside main
, so in fact n
is
never null
.
You can fix this problem in several ways:
head
node in for printing, deletions, etc., orNode
objects to return the modified list - this would let you insert new nodes or delete the head node, orMyList
class that owns all nodes - move all list operations on the "umbrella" class, and deal with the head
node there.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With