Find the node right before your node to remove.
If not null, set the node.next to note_to_remove.next
Else -> Node was head so set head to node_to_remove.next
Safely remove the Node
public class MyLinkedList
MyNode
public void add(E data) {
MyNode n= new MyNode(data);
n.next= head;
head= n;
}
public void delete(E element) {
MyNode prev= null, current= head;
}
public boolean find(E element) {
MyNode current= head;
while (current != null && !current.element.equals(element))
current= current.next;
if (current != null)
return true;
else return false;
}
public String toString() {
String result= "";
MyNode current= head;
while (current != null) {
result += current.element + " ";
current= current.next;
}
return result;
}
public void insertElementBefore(E element, E newElement) {
MyNode prev= null, current= head;
MyNode n;
while (current != null && !current.element.equals(element)) {
prev= current;
current= current.next;
}
}
}