Linked List递归removeAll方法

时间:2013-07-01 23:33:55

标签: java recursion linked-list singly-linked-list removeall

我正在尝试定义一个递归方法,该方法删除单链接列表中等于目标值的所有实例。我定义了一个remove方法和一个附带的removeAux方法。如何改变这一点,如果需要移除头部,头部也会被重新分配?以下是我到目前为止的情况:

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

2 个答案:

答案 0 :(得分:0)

我更喜欢在您删除之前切换前一个类似

之前切换的引用
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);
    }
}

检查此答案graphically linked list可能会帮助您思考如何实施它。 如果这对培训是好的,但你可以迭代的方式做。

答案 1 :(得分:0)

你可以试着塑造你的功能,使它像这样工作。

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

我从Coursera的算法课中学到的一个巧妙的技巧。

其余代码如下。

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
}