gpt4 book ai didi

java - 使用递归java从链表中删除节点

转载 作者:行者123 更新时间:2023-11-30 09:30:03 26 4
gpt4 key购买 nike

所以我有一个链表,我希望能够删除第一次出现的数字,

我正在尝试使用递归,但遗憾的是我最终所做的只是能够删除列表的头部和

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com