所以我有一个链表,我希望能够删除第一次出现的数字,
我试图使用递归但遗憾的是我最终做的就是能够删除列表的头部并且
public List remove(int num){
if(value == num) {
return next.remove(value);
}else{
next = next.remove(value);
return this;
}
}
我知道我需要返回新的列表,但是我究竟是如何摆脱我试图避免的节点或是否有办法解决它,所以它继续下一个点头
编辑。更新实际代码。
class List{
int value; //value at this node
List next; //reference to next object in list
public List(int value, List next){
this.value = value;
this.next = next;
}
}
我有三个不同的类,一个用于此末尾的空列表,一个类声明此方法,以及实际列表。
public static List makeSample() {
EmptyList e = new EmptyList();
List l1 = new List(5, e);
List l2 = new List(4, l1);
List l3 = new List(3, l2);
List l4 = new List(3, l3);
List l5 = new List(2, l4);
List l6 = new List(1, l5);
return l6;
}
答案 0 :(得分:2)
试试这个
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class List {
private int value;
private List next;
public static final List EMPTY = new List(-1, null) {
public List remove(int n) { return this; };
public String toString() { return ""; };
};
public List(int value, List next) {
this.value = value;
this.next = next;
}
public List remove(int n) {
if (value == n) return next;
return new List(value,next.remove(n));
}
public String toString() {
return value + "," + next.toString();
}
public static class Examples {
@Test
public void shouldRemoveElement() {
List l = new List(1, new List(2, new List(2, new List(3, EMPTY))));
assertEquals("1,2,2,3,",l.toString());
assertEquals("2,2,3,",l.remove(1).toString());
assertEquals("1,2,3,",l.remove(2).toString());
assertEquals("1,2,2,",l.remove(3).toString());
assertEquals("1,2,2,3,",l.toString());
}
}
}
答案 1 :(得分:0)
保留两个清单。
List nonDuplicates;
List allElements;
for (Node node : allElements){
if (!nonDuplicates.contains(node)){
nonDuplicates.add(node);
}
}