java - 如何从不可变链表中删除?
问题描述
我需要使用 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;
}
推荐阅读
- web-services - Coldfusion 2021 (java 11) 上的 Web 服务中断
- docker - 使用 Flask Swagger 在云端加载 API 定义失败
- google-apps-script - 有没有办法跟踪 Google 表格用户的电子邮件?
- cats-effect - 当前 cat-effects IO 错误处理技术的现状如何?
- c# - 我需要帮助弄清楚如何将浮点值等转移到我的武器系统中的另一个脚本中
- flutter - Flutter 中的同步机制
- sap-cloud-sdk - SAP OData 生成器为导航条目生成错误 URL
- python - opengl 漫射光变得奇怪的方向性,但不会根据 GL_SPOT_DIRECTION 改变
- video - 在 Android 设备上录制视频时,有没有办法编辑 CRF 值?
- python - Nginx 和 Gunicorn 与 Docker - 如何限制对 Flask 应用程序的访问仅限于 nginx?