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

标签 java list recursion linked-list

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

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

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/

相关文章:

c++ - 当有2个或多个递归函数写在一起时程序如何执行?

memory - Haskell 递归和内存使用

haskell - 此折叠实现中的错误

java - Mapreduce 映射器将键和值作为文本字段传递

javascript - 如何将数据发送到 Controller ,例如模型具有列表模型AngularJs

java - 如何通过传递搜索字符串在浏览器中显示 pdf 文件,并且需要使用 java 显示第一个包含突出显示的搜索字符串的页面

python - 基于 'for' 循环变量创建新列表

java - 删除单链表的最后一个元素不起作用

java - 如何安装jtransc?

java - JAVA中的物理地址