我需要使用remove()方法创建一个链表,该方法接受一个参数e,一个通用的替代品,并删除包含e的链接节点,然后该方法返回一个新的链表,其中包含除e.
我不知道如何实现这个,我得到的最远的是:
public Set<E> remove(E e) {
LinkedNode<E> current = null;
if(!this.contains(e)) {//if this list doesnt contain e, return this
return this;
} else {//otherwise go through this set and if it contains e return new set w/out it
for(E j:this) {
if(j.equals(e)) {
current = new LinkedNode<E>(j,current);
}
}
}
Set<E> newSet = new LinkedSet<E>(current);
for(E i:newSet) {
System.out.print(i +", ");
}
return newSet;
}
此代码使用迭代器,因此增强的 for 循环可以工作,但它返回包含错误信息的集合。我认为这可能是因为我想要的新集合的尾部仍然具有指向旧列表末尾的链接,但这只是一个猜测。
我得到的最后一个输出是:d, b, a, c, e, b, d, a, c, e, b, d, a, 输入为:c,a,d,b,e
我试图删除 c
最佳答案
假设您从 remove()
方法返回剩余元素,您可以添加不是 e
的每个元素:
public Set<E> remove(E e) {
Set<E> newSet = new LinkedSet<E>();
for(E j : this) {
if (!j.equals(e)) {
newSet.add(j);
}
}
return newSet;
}
关于java - 如何从不可变链表中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700294/