Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insertion in a linked list having head as null

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?.

like image 553
SaravananKS Avatar asked Nov 21 '17 15:11

SaravananKS


1 Answers

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:

  • Treat the head node in a special way - ignore the head node in for printing, deletions, etc., or
  • Change methods that operate on Node objects to return the modified list - this would let you insert new nodes or delete the head node, or
  • Introduce a MyList class that owns all nodes - move all list operations on the "umbrella" class, and deal with the head node there.
like image 128
Sergey Kalinichenko Avatar answered Sep 18 '22 23:09

Sergey Kalinichenko