简体   繁体   English

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

[英]Removing a node from a linked list using recursion java

So i have a linked list that I want to be able to remove the first occurrence of a number,所以我有一个链表,我希望能够删除第一次出现的数字,

I'm trying to use recursion but sadly all I end up doing is being able to delete the head of the list and我正在尝试使用递归,但遗憾的是我最终做的就是能够删除列表的头部和

public List remove(int num){
   if(value == num) {
       return next.remove(value);
   }else{
       next = next.remove(value);
       return this;
   }
}

I know i need to return the new list, but how exactly do i either get rid of the node that I'm trying to avoid or is there a way to work around it, so it continues to the next nod.我知道我需要返回新列表,但是我究竟如何摆脱我试图避免的节点或有办法解决它,所以它继续下一个点头。

Edit.编辑。 Update on the actual code.更新实际代码。

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;
  }
}

I have three different classes, one for the empty list at the end of this, and a class declaring this method, and the actual list.我有三个不同的类,一个是最后的空列表,一个是声明这个方法的类,还有实际的列表。

  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;
    }

Try this尝试这个

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());
        }

    }

}

Keep two lists.保留两个清单。

List nonDuplicates;

List allElements;

for (Node node : allElements){
    if (!nonDuplicates.contains(node)){
        nonDuplicates.add(node);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM