如何递归删除列表中具有特定值的节点

时间:2018-09-25 07:13:52

标签: java loops recursion data-structures

我已经提供了删除一个或多个元素的代码,但是现在我想递归地删除它。例如,如果要删除元素5,它将遍历列表并找到找到的所有5个元素,然后将其删除。

这是代码:

private class Node {

    private T value;
    private Node next;

    private Node(T value, Node next) {
        this.value = value;
        this.next = next;
    }

//    private Node() {

//    }
}

private Node head;


public void delete(T element) {

    Node current = head;
    if(current.value == element){
        head = current.next;
    }
    current = head;
    Node toDelete = current.next;

    while (current.next != null) {
        while (toDelete.value != element) {
            current = current.next;
            if (current.next == null) {
                return;
            }
            toDelete = current.next;
        }
        if (toDelete.value == element) {
            current.next = toDelete.next;
            toDelete = current.next;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public void delete(T element) {
    //In case, list is empty. 
    if(head == null) return;

    //If the head's value equals element, replace the head with its successor.
    if(head.value == element){
        head = head.next;
        delete(element);
        return;
    }
    //recursive call, if the head's value doesn't equal to the element anymore.
    delete_helper(element,head,head.next)
}

public void delete_helper(T element, Node pre, Node curr){
    //In case, curr's predecessor was the last element in the list.
    if(curr == null) return;

    //If the current value equals the element, skip the current node
    if(element == curr.value){
        pre.next = curr.next;
        delete_helper(element,pre,curr.next);
        return;
    }

    //recursive call with next node.
    delete_helper(element,curr,curr.next);
}