Following is my try : –
public void removeTail(){
Node precurrent=null;
Node transverse=head;
if(size != 0) {
while(transverse.getNext() !=null) {
System.out.println("oh"+transverse.getElement());
precurrent=transverse;
transverse=transverse.getNext();
}
precurrent.setNext(null);
size--;
}
else{
System.out.println("List is all ready empty");
}
}
The problem with above code is that it gives error when there is only one node left and I try to remove it. This is because of the way I defined precurrent. Kindly suggest what should be done to handle this case. I don’t want to add the case of size==1.
There are two possible ways.
Either check if your size equals to 1.
Or and this would be my solution, initialize
precurrentwithheadjust like you did it withtransverse