从链接列表中递归查找和删除节点

时间:2015-04-09 11:58:26

标签: java recursion linked-list nodes

给定要搜索的字符串,我想编写一个递归函数,只接受一个参数(要搜索的字符串)。该函数将以递归方式搜索该值,如果找到该值,则会删除该项并将其返回。如果未找到,则该函数将到达列表的末尾并返回null。到目前为止,我认为是正确的想法,除非它没有正常运作:

主要测试类

public static void main(String[] args) {
    RecLinkedList list = new RecLinkedList();
    list.add("A");
    list.add("B");
    list.add("D");
    list.add("C", 2);
    list.add("E", 4);
    list.add("G", 6); //this should be invalid

    System.out.println( list );
    System.out.println( list.remove( 1 ).getValue() );
    System.out.println( list.remove("D").getValue() );
    System.out.println( list.remove("G").getValue() );
    System.out.println( list.size() );
    System.out.println( list );
}

链接列表类(仅显示我需要的帮助)

public class RecLinkedList {
private Node first;
private int size = 0;

public RecLinkedList(){
    first = null;
}
public boolean isEmpty() {
    return first == null;
}
public Node remove( String s ){
    return remove( s, 0, first );
}
private Node remove( String s, int count, Node list ){
    if( list == null ){
        return null;
    }else if( s.equals(s) ){
        first = list.getNext();
        return list;
    }else if( s.equals(count+1) ){
        Node n = list.getNext();
        if( list.getNext() != null ){
            list.setNext( list.getNext().getNext() );
        }
        return n;
    }else{
        return remove( s, count+1, list.getNext() );
    }
}

到目前为止,我可以删除该项目但截至目前该项目" A"当它不应该被删除。最终的清单应该是A,C,E。 (G应返回并打印null,因为它不存在)。我认为我很接近,但是接近一些小事,但我似乎无法弄明白。

2 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误(请参阅下面的评论):

private Node remove( String s, int count, Node list ){
    if( list == null ){
        return null;
    }else if( s.equals(s) ){ // comparing s to itself means you always remove
                             // the first element from the list (since this
                             // condition is always true)
        first = list.getNext();
        return list;
    }else if( s.equals(count+1) ){ // comparing the String s to an int - makes
                                   // no sense, will never be true
        Node n = list.getNext();
        if( list.getNext() != null ){
            list.setNext( list.getNext().getNext() );
        }
        return n;
    }else{
        return remove( s, count+1, list.getNext() );
    }
}

答案 1 :(得分:0)

在我看来,你的问题有些含糊不清。我知道你的方法应该搜索一个元素,如果存在则删除它,并返回相同的对象。如果元素不存在,则该方法应返回null。这似乎很简单,因为大多数实用方法已经在LinkedList中实现了。因此,我建议扩展该课程:

public class RecLinkedList<E>
    extends LinkedList<E>
{
    public E removeAndReturn(E element)
    {
        E result;
        if (this.contains(element)) {
            remove(element);
            result = element;
        }
        else {
            result = null;
        }
        return result;
    }
}

我不明白为什么你想要递归地实现这个。

这显然可以更简洁地书写,但明确的if-else应该更清楚。

编辑:更简洁,可能更好的实施方式是:

public E removeAndReturn(E element)
{
    return remove(element) ? element : null;
}