Другими словами, у меня есть линия объектов Dancer.
public class Dancer {
private String name;
private Dancer next;
public Dancer(String nameInput, Dancer followingDancer){
name = nameInput;
next = followingDancer;
}
У меня есть сеттеры и геттеры для них.
Чтобы связать их вместе, у меня есть CongaLine.
public class CongaLine {
private Dancer head; // first dancer in the conga line.
public CongaLine() {
head = null;
}
Итак, используя цикл while, чтобы найти ближайшего к последнему Dancer, как мне найти извлечение последнего Dancer из CongaLine?
Мой текущий метод, который имеет недостатки, выглядит так:
public String removeFromEnd() {
String removed = null;
// For multiple dancers, find the penultimate and remove its "next"
while (head.getNext() != null) {
if (head.getNext().getNext() == null){
removed = head.getNext().getName();
head.setNext(null);
}
}
// In the case of only one dancer, remove that dancer.
if (head != null && head.getNext() == null) {
removed = head.getName();
head = null;
}
return removed;
}