Search code examples
javadata-structureslinked-list

If we check head==null why don't we check tail==null in Java linkedlist?


I am a beginner in Java and currently completing a Udemy course on DSA. I am learning linked lists and am working on methods to insert and delete nodes to and from linked lists respectively.

From what I have learnt so far I know that we use condition head==null to check if the linked list is empty or not.

If the condition head==null is true then LinkedList is empty else it is not empty.

However, shouldn't we check whether tail==null as well because the tail will always refer to the last node in the LinkedList even after we make head==null?

Here is my code:

public class SinglyLinkedList{
  public Node head;
  public Node tail;
  public int size;

//Create Linkedlist
  public Node createLL(int num){
    Node node=new Node();
    node.value=num;
    node.next=null;
    head=node;
    tail=node;

    size=1;
    return head;
  }
//Insert Node
  public void insertNode(int num,int location){
    Node node=new Node();
    node.value=num;
    
    if(head==null){//Used to check if linked list is empty or not?
      createLL(num);
      return;
    }

    else if(location==0){
      node.next=head;
      head=node;
    }

    else if(location>=size){
      node.next=null;
      tail.next=node;
      tail=node;
    }

    else{
      Node tempNode=head;
      int index=0;

      while(index<location-1){
        tempNode=tempNode.next;
        index++;
      }
     node.next=tempNode.next;
     tempNode.next=node;
    }
    size++;
  }
//Delete Node
  public void deleteNode(int location){
    if(head==null){//Used to check if linked list is empty or not?
      System.out.println("The linked list is not present");
      return;
    }

    else if(location==0){
      head=head.next;
      size--;
      if(size==0){
        tail=null;
      }
    }

    else if(location>=size){
      Node tempNode=head;
      for(int i=0;i<size-1;i++){
        tempNode=tempNode.next;
      }
      if(head==null){
        tail=null;
        size--;
        return;
      }
      tempNode.next=null;
      tail=tempNode;
      size--;
    }

    else{
      Node tempNode=head;
      int index=0;

      while(index<location-1){
        tempNode=tempNode.next;
        index++;
      }
      tempNode.next=tempNode.next.next;
      size--;
    }
  }
}

Solution

  • Empty list:

    head -> null
    tail -> null
    

    Single node list:

    head -> node1
    node1.next -> null
    tail -> node1
    

    Multi node list:

    head -> node1
    node1.next -> node2
    node2.next -> null
    tail -> node2
    

    Where -> means "reference points to". So there's no need to check for both head/tail for nullness. If either of them is null, it means the list has no nodes and is empty.