A linked list is type of data structure that contains items in linear order. Deleting an item from linked list performs O(n) time complexity. you can perform two type of deletion from linked list either you can delete first item of list or in any given position of item.
Here is an example of deletion from last node :
public void deleteAtLast(){
Node<T> tempNode;
Node<T> head;
Node<T> trail;
if( head == null){
trail = null;
break;
}else{
tempNode = head.getNextNode();
head = tempNode;
}
}
or you can delete a node after a given node like this :
public void deleteAfter(T element){
Node<T> tempNode = head;
Node<T> refNode = null;
while (true){
if (head == null){
break;
}else{
if (tempNode.compareTo(element) == 0){
refNode = tempNode;
break;
}
}
tempNode = tempNode.getNextReference();
}
if (refNode != null){
tempNode = refNode.getNextReference();
refNode.setNextReference(tempNode.getNextReference());
if (tempNode.getNextReference() == null){
trail = refNode;
}
}
}
0 Comment(s)