Java 如何从相互连接的一行对象的末端删除对象?(爪哇)
换句话说,我有一排舞者对象Java 如何从相互连接的一行对象的末端删除对象?(爪哇),java,object,loops,while-loop,Java,Object,Loops,While Loop,换句话说,我有一排舞者对象 public class Dancer { private String name; private Dancer next; public Dancer(String nameInput, Dancer followingDancer){ name = nameInput; next = followingDancer; } 我有二传手和接球手 要把这些串起来,我有一根绳子 public clas
public class Dancer {
private String name;
private Dancer next;
public Dancer(String nameInput, Dancer followingDancer){
name = nameInput;
next = followingDancer;
}
我有二传手和接球手
要把这些串起来,我有一根绳子
public class CongaLine {
private Dancer head; // first dancer in the conga line.
public CongaLine() {
head = null;
}
那么,使用while循环来查找下一个到最后一个舞者,我如何从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;
}
这是一个很好的例子。你必须在舞者中循环,直到你到达康加舞的终点:
Dancer d = congaLine.getHead();
while(d.getNext() != null) {
d = d.getNext();
}
在这场比赛结束时,d将是最后一位舞蹈演员。
您只需要为dancer中的下一个舞者和CongaLine中的头舞者实现一个getter。这是一个示例。你必须在舞者中循环,直到你到达康加舞的终点:
public class CongaLine {
private Dancer head; // first dancer in the conga line.
public CongaLine() {
head = null;
}
Dancer d = congaLine.getHead();
while(d.getNext() != null) {
d = d.getNext();
}
在这场比赛结束时,d将是最后一位舞蹈演员。
您只需要为dancer中的next
dancer和CongaLine中的head
dancer实现一个getter。嗯,我可以给您提供确切的代码(只需几行),但是我认为,既然您这样做是为了学习,最好给出一些提示:
public class CongaLine {
private Dancer head; // first dancer in the conga line.
public CongaLine() {
head = null;
}
- 想想最后一个舞者有什么属性可以用来识别它
- 想一想你如何确保你看所有的舞者,这样你就能找到一个拥有正确属性的舞者
- 思考还需要进行哪些更改(例如,对倒数第二个舞者),以及如何确保这些更改始终发生
嗯,我可以给你确切的代码(只有几行),但是我认为,既然你这样做是为了学习,那么最好给出一些提示:
- 想想最后一个舞者有什么属性可以用来识别它
- 想一想你如何确保你看所有的舞者,这样你就能找到一个拥有正确属性的舞者
- 思考还需要进行哪些更改(例如,对倒数第二个舞者),以及如何确保这些更改始终发生
可能会找到几个例子。可能会找到几个例子。别难过,这都是学习体验的一部分!我已经写了26年了,但我的代码仍然一直出错。。。。重要的是锻炼你的思维,尝试不同的解决方案,以便在问题发生时找到解决问题的好方法。:-)该地产将是它的“下一个”。它将是空的。第二颗子弹我不确定。我很确定我需要将下一个到最后一个舞者的“下一个”设置为空。我还需要返回null或删除的dancer。我就是不能理解我的方法中缺少了什么。好的开始!现在,也许可以尝试在Dancer类中编写一个返回布尔值的方法“isLastDancer()。如果你把一些复杂的功能划分成明确命名的函数,通常会使你更容易调试逻辑。我可能是想让事情变得更难。不管怎样,我都无法让这种方法发挥作用。别难过——这都是学习经验的一部分!我已经写了26年了,但我的代码仍然一直出错。。。。重要的是锻炼你的思维,尝试不同的解决方案,以便在问题发生时找到解决问题的好方法。:-)该地产将是它的“下一个”。它将是空的。第二颗子弹我不确定。我很确定我需要将下一个到最后一个舞者的“下一个”设置为空。我还需要返回null或删除的dancer。我就是不能理解我的方法中缺少了什么。好的开始!现在,也许可以尝试在Dancer类中编写一个返回布尔值的方法“isLastDancer()。如果你把一些复杂的功能划分成明确命名的函数,通常会使你更容易调试逻辑。我可能是想让事情变得更难。无论如何,我都无法使该方法起作用。在您的CongaLine类中,为什么没有类型为的字段?类似于private List dancer=new LinkedList();然后你可以得到dancer.getLast()这个例子,这会让它变得太简单。我需要在不更改预定义类的情况下执行此操作。在您的CongaLine类中,为什么没有类型为的字段?类似于private List dancer=new LinkedList();然后你可以得到dancer.getLast()这个例子,这会让它变得太简单。我需要在不改变预定义类的情况下完成它。