我想定義一個遞歸方法,它刪除單鏈表中等於目標值的所有實例。我定義了一個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_,那麼遞歸將是適當的。 –
如果您有時間,請查看我的解決方案 –