0
  public class Node {
        public int data;
        public Node next;
        public Node(){
            data=0;
            next=null;
        }
        public Node(int x){
            data=x;
            next=null;
        }
    }

The above code is the class Node, where it contains data and next variables. Using this class observe the following code:

public class SinglyLinkedList {
public Node head=null;
public  void insert_at_head(int x){
    Node newnode=new Node(x);
    if(head==null){
        head=newnode;
    }
    else{
        newnode.next=head;
        head=newnode;
    }
}

At line 2 head of type Node is initialized to null. What is actually happening here? Is it equal to initializing head.data and head.next to null?

yuriy636
  • 11,171
  • 5
  • 37
  • 42
Vemuri Pavan
  • 495
  • 7
  • 15
  • Just for the record: that assignment next=null is actually pointless - `null` is the default value that any reference type object has initially. Then: read about java naming conventions. You dont use "_" in method names - it is only for SOME_CONSTANT. – GhostCat Sep 05 '17 at 14:51
  • Since `Node.next` is initialized to `null`, the entire conditional can be eliminated, because the end result of calling `insert_at_head` is going to be the same no matter what branch the code takes. The code below will perform the same operation without a conditional: `public void insert_at_head(int x){ Node newnode=new Node(x); newnode.next=head; head=newnode; }` – Sergey Kalinichenko Sep 05 '17 at 14:52

0 Answers0