所以我有一个链接列表,我希望能够删除第一次出现的数字,
我正在尝试使用递归,但遗憾的是我最终所做的就是能够删除列表的头部和
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;
}
最佳答案
试试这个
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());
}
}
}
关于java - 使用递归java从链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13436878/