[英]Java linked list recursive methods
I don't understand the linked list data structure and how the recursion works in it.我不了解链表数据结构以及递归如何在其中工作。 I understand normal recursion but with linked lists not at all.
我理解正常的递归,但完全不理解链表。
The code is below is a linked list class with A
elements.下面的代码是一个带有
A
元素的链表类。 It has a head as A
element and the rest of the list(tail) as another linked list.它有一个头部作为
A
元素,列表的其余部分(尾部)作为另一个链表。
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class LL<A> {
private final A hd;
private final LL<A> tl;
public boolean isEmpty(){
return hd==null && tl==null;
}
public LL(A hd, LL<A> tl) {
this.hd = hd;
this.tl = tl;
}
public LL() {
this(null,null);
}
public int size() {
if (isEmpty())
return 0;
return 1 + tl.size();
}
public A get(int i) {
return i==0?hd:tl.get(i-1);
}
LL<A> drop(int i){
if(i==0) return this;
if(i<0) return new LL<>();
if(isEmpty()) return new LL<A>();
return this.tl.drop(i-1);
}
}
So for example this drop method creates a new linked list with the elements other than the first i
elements.因此,例如这个 drop 方法创建一个新的链表,其中包含除前
i
元素之外的元素。 I don't get how it works.我不明白它是如何工作的。 Let's say if I call
drop(1)
on a linked list what will it do step by step?假设我在链表上调用
drop(1)
它将逐步做什么?
drop
only creates a new list in special cases. drop
仅在特殊情况下创建一个新列表。
If the list has n elements and you call drop(i) where i < n, it doesn't create a new list.如果列表有 n 个元素并且您在 i < n 处调用 drop(i),它不会创建新列表。 It simply returns the
i+1
'th link of the list, which is equivalent to the original list with the first i
elements removed.它只是返回列表的第
i+1
个链接,这相当于删除了前i
元素的原始列表。
this.tl
is the tail of the list references by this
, which in other words means this.tl
is the list you get from this
after removing the first element. this.tl
是列表中引用的尾巴this
,这在其他的字的装置this.tl
是你从获取列表this
除去第一元素之后。
For example, assuming a list has at least one element, drop(1)
will return this.tl.drop(0)
, which will return this.tl
- ie the original list without the first element.例如,假设一个列表至少有一个元素,
drop(1)
将返回this.tl.drop(0)
,这将返回this.tl
- 即没有第一个元素的原始列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.