简体   繁体   中英

Linked List Recursive removeAll method

I'm trying to define a recursive method that removes all instances in the singly-linked list that are equal to the target value. I defined a remove method and an accompanying removeAux method. How can I change this so that if the head needs to be removed, the head is reassigned as well? Here is what I have so far:

public class LinkedList<T extends Comparable<T>> {

private class Node {
    private T data;
    private Node next;

    private Node(T data) {
        this.data = data;
        next = null;
    }
}

private Node head;

public LinkedList() {
    head = null;
}

public void remove(T target) {
    if (head == null) {
        return;
    }

    while (target.compareTo(head.data) == 0) {
        head = head.next;
    }

    removeAux(target, head, null);
}

public void removeAux(T target, Node current, Node previous) {
    if (target.compareTo(current.data) == 0) {
        if (previous == null) {
            head = current.next;
        } else {
            previous.next = current.next;
        }
        current = current.next;
        removeAux(target, current, previous); // previous doesn't change

    } else {
        removeAux(target, current.next, current);
    }
}

I prefer to pass a reference to the previous when you remove to switch previous to the next something like this

public void remove(T target){
   removeAux(target,head, null);
}


public void removeAux(T target, Node current, Node previous) {
      //case base
       if(current == null)
               return;

    if (target.compareTo(current.data) == 0) {

        if (previous == null) {
          // is the head
            head = current.next;
        } else {
            //is not the head
            previous.next = current.next;
        }
        current = current.next;
        removeAux(target, current, previous); // previous doesn't change

    } else {
        removeAux(target, current.next, current);
    }
}

Check this answer graphically linked list may help you to think how to implement it. If this for training is good but you can do in iterative way.

You could try to fashion your function so that it works like this.

 head = removeAux(target, head); // returns new head

A neat trick I learn't from Coursera's Algorithms classes.

The rest of the code is as follows.

public void removeAux(T target, Node current) {
  //case base
   if(current == null)
           return null;

   current.next = removeAux(target, current.next);

   return target.compareTo(current.data) == 0? current.next: current; // the actual deleting happens here
}

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