换句话说,我有一行 Dancer 对象。
public class Dancer {
private String name;
private Dancer next;
public Dancer(String nameInput, Dancer followingDancer){
name = nameInput;
next = followingDancer;
}
我有这些的 setter 和 getter。
为了将这些串起来,我有一个 CongaLine。
public class CongaLine {
private Dancer head; // first dancer in the conga line.
public CongaLine() {
head = null;
}
那么,使用 while 循环查找倒数第二个 Dancer,我如何找到从 CongaLine 中提取的最后一个 Dancer?
我目前的方法是有缺陷的,如下所示:
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;
}
最佳答案
嗯,我可以给你确切的代码(只有几行),但我认为既然你这样做是为了学习,最好给出一些提示:
- 想想最后的舞者有什么属性可以用来识别它。
- 想一想如何确保您审视所有舞者,以便找到具有合适属性的舞者。
- 考虑需要发生哪些其他变化(例如倒数第二个舞者),以及如何确保始终发生这些变化。
关于java - 如何从相互连接的一排对象的末尾删除一个对象? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9406084/