使用递归删除链表中元素的所有出现

时间:2019-04-21 01:15:53

标签: java recursion data-structures linked-list

我正在实现Linked-List数据结构,并且希望通过递归来实现所有元素出现的remove方法,这是我的代码片段:

public class MyLinkedList<T> {
  private Node<T> head;
  private Node<T> last;
  private int length;

  public void remove(T elem) {
    if (!(this.isContained(elem)) || this.isEmpty())
      return;
    else {
      if (head.value.equals(elem)) {
        head = head.next;
        length--;
        remove(elem);
      } else {
        // This is a constructor which requieres a head and last, and a length
        new MyLinkedList<>(head.next, last, length-1).remove(elem);
      }
    }
  }
}

我确实了解问题所在,我正在处理列表的副本而不是原始列表,因此,如何合并此子列表或使其成为原始列表?

2 个答案:

答案 0 :(得分:0)

如果我必须进行递归操作,我认为它看起来像这样:

public void remove(T elem)
{
    removeHelper(null, this.head, elem);
}

private void removeHelper(Node<T> prev, Node<T> head, T elem)
{
    if (head != null) {
        if (head.value.equals(elem)) {
            if (head == this.head) {
                this.head = head.next;
            } else {
                prev.next = head.next;
            }
            if (this.last == head) {
                this.last = prev;
            }
            --this.length;
        } else {
            prev = head;
        }
        removeHelper(prev, head.next, elem);
    }
}

出于记录,如果我不必必须使用递归,则可以像这样线性进行:

private void remove(T elem)
{
    Node<T> prev = null;
    Node<T> curr = this.head;
    while (curr != null) {
        if (curr.value.equals(elem)) {
            if (this.last == curr) {
                this.last = prev;
            }
            if (prev == null) {
                this.head = curr.next;
            } else {
                prev.next = curr.next;
            }
            --this.length;
        } else {
            prev = curr;
        }
        curr = curr.next;
    }
}

答案 1 :(得分:0)

我建议您在单独的静态函数中执行此操作,而不是在实际的节点类中执行此操作,因为您要遍历整个链表。

public void removeAllOccurences(Node<T> head, Node<T> prev, T elem) {
    if (head == null) {
      return;
    }
    if (head.value.equals(elem)) {
      Node<T> temp = head.next;
      if (prev  != null) {
        prev.next = temp;
      }
      head.next = null; // The GC will do the rest.
      removeAllOccurences(temp, prev, elem);
    } else {
      removeAllOccurences(head.next, head, elem);
    }
  }