Мой метод int deleteLast() должен удалить последний узел, а также вернуть значение внутри удаляемого узла. мой код, похоже, не работает. он не удаляет последний узел. Любая помощь будет оценена.удаление последнего узла из одноуровневого списка (java)
импорт java.util.NoSuchElementException; импорт java.util.Scanner;
общественного класса LinkedList11 { // Частный внутренний класс Node
private class Node{
int data;
Node link;
public Node(){
data = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public LinkedList11(){
head = null;
}
public int deleteLast() throws NoSuchElementException {
if (head == null) //handle when list is empty
{ throw new NoSuchElementException();}
if(head.link == null) //handle when head is the only node
{ return head.data;
}
Node position = head;
Node temp = head; //temp has to be initialized to something
int dataAtEnd =0;
while (position != null)
{ dataAtEnd = position.data;
temp =position; //safe keep current position
position = position.link; //update position pointer to get the next value
}
position =temp; // store current position in next position
return dataAtEnd;
}
}
Большое спасибо за объяснение. Просто протестировал его, работает. –