문제

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top