Я делаю отдельный список, где мне нужно поместить метод удаления, но получить любую помощь?Единственный связанный список Удалить значение
public void remove(int index) {
getNode(index - 1).Next = getNode(index + 1);
}
Я делаю отдельный список, где мне нужно поместить метод удаления, но получить любую помощь?Единственный связанный список Удалить значение
public void remove(int index) {
getNode(index - 1).Next = getNode(index + 1);
}
Здесь возможно много возможных ошибок. Во-первых, я окончательно поставил бы больше проверки, прежде чем вносить какие-либо изменения, как если бы
Как правильно сказал Апокай, вы должны проявлять особую осторожность при удалении.
Вот три метода для удаления использования в зависимости от того служит цели:
//Method to delete the first/head element
public void deleteAtFirst() {
if (head == null) {//If list is empty
System.out.println("Linked List EMPTY!!");
} else {//else if it is not empty
head = head.next;//assigning head the address of the next node
}
}
//Method to delete the last element
public void deleteAtLast() {
if (head == null) {//If list is empty
System.out.println("Linked List EMPTY!!");
} else if (head.next == null) {//else if it has only 2 elements
head = null;
} else {//else if it is not empty and has more than 2 elements
Node tmpNode = head;//taking a temporary node and initialising it with the first/head node
while (tmpNode.next.next != null) {//looping it till the 'second last' element is reached
tmpNode = tmpNode.next;
}
tmpNode.next = null;//assigning the next address of the second last node as null thus making it the last node
}
}
//Method to delete an element at a given position
//The first element is situated at 'Position:[0]'
public void deleteAtPosition(int pos) {
int size = getSize();//Getting the size of the linked list through a pre-defined method
if (head == null || pos > size - 1) {//if the position is beyond the scope of current list or the list is empty
System.out.println("Position: " + pos + "does not exist");
} else {
Node prevNode = null;
Node currNode = head;
if (pos == size - 1) {//if position is equal to size-1 then essentially the last element is to be deleted
deleteAtLast();
} else if (pos == 0) {//if position given is '0' then we need to delete the first element
deleteAtFirst();
} else {//else if it is any other valid position
for (int i = 0; i < pos; i++) {//looping till the desired position
prevNode = currNode;//the node just before the required position will be assigned here
currNode = currNode.next;//the current node
}
prevNode.next = currNode.next;//assigning the next address of previous node to the next of current node thus removing the current node from the list
}
}
}
Береги, что если вы используете один последний то вышеуказанные два метода присутствуют в вашем коде. Также он использует другой метод getSize():
//Method to get the size of the list
public int getSize() {//return type is integer as we are returning 'int size'
if (head == null) {//if the list is empty
return 0;
}
int size = 1;//initialising size by one
Node tmpNode = head;//taking a temporary node and initialising it with the first/head node
while (tmpNode.next != null) {//looping till the end of the list
tmpNode = tmpNode.next;//incrementing node to the next node 'after every iteration' of the loop
size++;//incrementing the size
}
return size;//returning size
}
Это может помочь, если вы сказали нам, что такое фактическая ошибка. Кроме того, этого фрагмента кода, скорее всего, недостаточно, чтобы определить проблему. – jpw