In java singly LinkedList how do I write code that nulls the tail(tail=null) when I null the head(head=null)? I am a beginner and hence find it difficult. I have included if(head==null)in every method but also want to implement code that sets tail=null when head=null so as to avoid a bug. Here is my code
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){
createLL(num);
return;
}
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){
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 boolean searchElement(int num){
Node tempNode=head;
for(int i=0;i<size;i++){
if(tempNode.value==num){
System.out.println("The value is present at index:"+i);
return true;
}
tempNode=tempNode.next;
}
System.out.println("The value is not present");
return false;
}
public void deleteNode(int location){
if(head==null){
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--;
head=tail=null;
}
else{
Node tempNode=head;
int index=0;
while(index<location-1){
tempNode=tempNode.next;
index++;
}
tempNode.next=tempNode.next.next;
size--;
}
}
public void deleteSinglyLinkedList(){
if(head==null){
System.out.println("The linkedlist is absent");
}
head=tail=null;
System.out.println("The entire linked list has been deleted");
}
}
if(head == null) tail = null;or(equvalent):if(head == null) tail = head;;)headdirectly.