Java 链表,通过返回新列表删除元素
使用Java,我有一个链接的LList类和一个LLNode类。我试图从我的链表中删除一个元素,方法是返回一个没有该元素的新链表。基本上,如果列表不包含特定元素,则返回它,但如果它确实创建了一个新元素,则返回它。我遍历当前列表,查看它是否包含元素e,但不确定如何创建没有该特定元素的列表Java 链表,通过返回新列表删除元素,java,linked-list,iterator,Java,Linked List,Iterator,使用Java,我有一个链接的LList类和一个LLNode类。我试图从我的链表中删除一个元素,方法是返回一个没有该元素的新链表。基本上,如果列表不包含特定元素,则返回它,但如果它确实创建了一个新元素,则返回它。我遍历当前列表,查看它是否包含元素e,但不确定如何创建没有该特定元素的列表 public LList<T> remove(T t) { if (this.contains(t)) { LList<T> newList = new LLSet<
public LList<T> remove(T t) {
if (this.contains(t)) {
LList<T> newList = new LLSet<>(this.head);
newList.head = new LLNode<>(, this.head);
return newList;
}
return this;
}
public-LList-remove(T){
如果(本文件包含(t)){
LList newList=new LLSet(this.head);
newList.head=新的LLNode(,this.head);
返回newList;
}
归还这个;
}
我假设LList和LLNodes是您自己的类。
我的第一个问题是,如果可以从同一个列表中删除元素并返回它,为什么要返回新列表?你应该做的是,
由于链表中有链接的节点,所以您可能应该
1.逐个遍历列表
2.并移除方法中传递的元素
但如果你真的想通过返回新列表来实现这一点。下面是你必须做的事情,
1.创建一个新列表
2.迭代旧列表并用旧列表中的元素填充新列表
3.跳过循环中要删除的元素
我的建议是,不要创建新列表,而是修改现有列表。这就是拥有LinkedList的好处。您必须用新节点构建一个新列表。如果尝试共享节点,则会对两个列表进行更改 我认为可以使用一个简单的
while
循环来创建新列表:
public LList<T> remove(T t) {
LList<T> newList = new LList<>();
LLNode<T> current = this.head;
while (current != null) {
if (!current.element.equals(t)) {
newList.add(t)
}
}
return newList;
}
public-LList-remove(T){
LList newList=新的LList();
LLNode current=this.head;
while(当前!=null){
如果(!current.element.等于(t)){
newList.add(t)
}
}
返回newList;
}
如果这确实是您想要的功能,并且您可以自由更改方法名称,我建议您在不使用(T)的情况下调用它
。大多数人都希望remove(T)
修改调用它的列表。假设remove方法在LList类中。试试这个:
public LList<T> remove(T t) {
LLNode curr = this.head;
LLNode prev = null;
while(curr != null) {
if (curr.equals(T)) {
prev.setNext(curr.next());
return this.head;
}
prev = curr;
curr = curr.next();
}
return this.head;
}
public-LList-remove(T){
LLNode curr=this.head;
LLNode prev=null;
while(curr!=null){
如果(电流等于(T)){
上一个setNext(curr.next());
把这个还给我;
}
上一次=当前;
curr=curr.next();
}
把这个还给我;
}