In java linked lists if head=null then the LinkedList is empty. However when I set head=null and print value of tail the value is displayed. Why is it that we say head==null means that the LinkedList is empty? Why is tail value being displayed when the linked list should be empty? Shouldn't we check id(tail==null)as well?
public class SinglyLinkedList{
public Node head;
public Node tail;
public int size;
public Node createLL(int num){
Node node=new Node();
node.value=num;
node.next=null;
head=node;
tail=node;
size=1;
return head;
}
public void insertNode(int num,int location){
Node node=new Node();
node.value=num;
if(head==null){//Check
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++;
}
public void traverse(){
if(head==null){//Check
System.out.println("The linked list is empty");
}
Node tempNode=head;
for(int i=0;i<size;i++){
System.out.print(tempNode.value);
if(i!=size-1){
System.out.print("->");
}
tempNode=tempNode.next;
}
System.out.println();
}
public void deleteNode(int location){
if(head==null){//Check
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--;
}
}
Main class
class Main {
public static void main(String[] args) {
SinglyLinkedList sLL=new SinglyLinkedList();
sLL.createLL(5);
sLL.insertNode(15, 1);
sLL.insertNode(20, 2);
sLL.insertNode(39, 3);
sLL.insertNode(45, 4);
sLL.traverse();
sLL.head=null;
System.out.println(sLL.tail.value);
}
}
Output: 5->15->20->39->45
45