首页 > 解决方案 > 如何从不可变链表中删除?

问题描述

我需要使用 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

标签: javalinked-listiterator

解决方案


假设您要从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;
}

推荐阅读