我正在尝试定义一个递归方法,该方法删除单链表中与目标值相等的所有实例。我定义了一个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);
}
}发布于 2013-07-02 07:44:20
当您移除切换到下一个时,我更喜欢传递对前一个的引用,如下所示
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可能会帮助您思考如何实现它。如果这对于训练是好的,但你可以用迭代的方式来做。
发布于 2013-07-02 07:53:08
你可以试着设计你的函数,让它像这样工作。
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
}https://stackoverflow.com/questions/17415285
复制相似问题