Я добавляю сюда фрагмент, чтобы удалить узел из SinglyLinkedList.Я предпочитаю forLoop более;Вот почему я добавил фрагмент с циклом for.
Надеюсь, что комментарий в коде поможет вам сориентироваться / пробежаться по фрагменту.
public boolean remove(int value){
Node oneBeforeValueNode;
// Using for to iterate through the SinglyLinkedList
// head → is the head of your SingleLinkedList
for (Node node = head; node != null; node = node.next) {
// Compare the value with current node
if (value.equals(node.data)) {
// if matches then unlink/remove that node from SinglyLinkedList
// if its a first node in SingleLinkedList
if(oneBeforeValueNode==null){
// Considering there exists next element else SLL will be empty
head = head.next;
} else {
// if there exists next element it SLL it will attach that element with previous one
oneBeforeValueNode.next = node.next;
}
return true;
}
// Storing previous node from current
// To use it once value is found to reference it to current.next(node.next)
oneBeforeValueNode = node;
}
return false;
}
Также добавляется вариант while;просто чтобы плыть по течению.
public Node remove(Node head, int key) {
Node current = head;
Node previous = null;
while (current != null) {
if(current.data == key) {
if(current == head) {
head = head.next;
current = head;
} else {
previous.next = current.next;
current = current.next;
}
} else {
previous = current;
current = current.next;
}
}
return head;
}