简体   繁体   中英

Remove all occurences of an element in a Linked List using recursion

I'm making the implementation of the Linked-List data structure and I'm looking foward to implement a remove method of all the occurrences of an element using recursion, here's a piece of my code:

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

I do understand the problem, I'm working with copies of a list not with the original, so, how could I merge or make this sub to the original list?

If I had to do it with recursion, I think it would look something like this:

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

For the record, if I didn't have to use recursion, I'd do it linearly like this:

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

I would suggest doing this in a separate static function instead of doing it in the actual node class since you are recursing through the entire linked list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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