![](/img/trans.png)
[英]how can I remove objects from my ArrayList that are also in other ArrayList in Java?
[英]How can I remove an object from the end of a line of objects connected to each other? (Java)
换句话说,我有一行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循环查找倒数第二个舞者,我如何从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
的结尾将是congaLine中的最后一位舞者。 您只需要为Dancer中的next
舞者和CongaLine中的head
舞者实现一个吸气剂即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.