[英]Remove all occurences of an element in a Linked List using recursion
我正在实现Linked-List数据结构,我正在寻找使用递归实现一个元素出现的remove
方法,这里是我的一段代码:
public class MyLinkedList<T> {
private Node<T> head;
private Node<T> last;
private int length;
public void remove(T elem) {
if (!(this.isContained(elem)) || this.isEmpty())
return;
else {
if (head.value.equals(elem)) {
head = head.next;
length--;
remove(elem);
} else {
// This is a constructor which requieres a head and last, and a length
new MyLinkedList<>(head.next, last, length-1).remove(elem);
}
}
}
}
我确实理解了这个问题,我正在使用不与原始列表一起列出的列表副本,那么,我怎么能合并或使这个子列表到原始列表?
如果我不得不用递归做,我认为它看起来像这样:
public void remove(T elem)
{
removeHelper(null, this.head, elem);
}
private void removeHelper(Node<T> prev, Node<T> head, T elem)
{
if (head != null) {
if (head.value.equals(elem)) {
if (head == this.head) {
this.head = head.next;
} else {
prev.next = head.next;
}
if (this.last == head) {
this.last = prev;
}
--this.length;
} else {
prev = head;
}
removeHelper(prev, head.next, elem);
}
}
为了记录,如果我不必使用递归,我会像这样线性地做:
private void remove(T elem)
{
Node<T> prev = null;
Node<T> curr = this.head;
while (curr != null) {
if (curr.value.equals(elem)) {
if (this.last == curr) {
this.last = prev;
}
if (prev == null) {
this.head = curr.next;
} else {
prev.next = curr.next;
}
--this.length;
} else {
prev = curr;
}
curr = curr.next;
}
}
我建议在一个单独的静态函数中执行此操作,而不是在实际的节点类中执行此操作,因为您将在整个链接列表中进行递归。
public void removeAllOccurences(Node<T> head, Node<T> prev, T elem) {
if (head == null) {
return;
}
if (head.value.equals(elem)) {
Node<T> temp = head.next;
if (prev != null) {
prev.next = temp;
}
head.next = null; // The GC will do the rest.
removeAllOccurences(temp, prev, elem);
} else {
removeAllOccurences(head.next, head, elem);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.