我想定义一个递归方法,它删除单链表中等于目标值的所有实例。我定义了一个remove方法和一个removeAux方法。我该如何改变这种情况,以便如果头部需要移除,头部也会重新分配?以下是我迄今为止:链接列表递归removeAll方法
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);
}
}
这是一个非常糟糕的数据结构和算法不匹配。列表是_linear_,在列表中使用递归没有多大意义。如果它是一个_tree_,那么递归将是适当的。 –
如果您有时间,请查看我的解决方案 –