[英]Recursively insert at the end of doubly linked list
I have a doubly linked list, and I want to insert an element at the end of the list recursively. 我有一个双向链表,我想递归地在列表末尾插入一个元素。 I have a method now that does this without recursion, and it works.
我现在有一个方法可以做到这一点而无需递归,并且可以正常工作。 I just can't seem to understand how to do it with recursion.
我似乎无法理解如何使用递归。 Inserting at the end of a singly linked list with recursion is quite easy to understand I think, so I hope that someone can explain how to it do it when the list is doubly linked.
我认为,在带有递归的单链接列表的末尾插入是很容易理解的,因此,我希望有人可以解释在双链接列表时如何执行此操作。 Here is my normal insertion method that I want to make recursive:
这是我要递归的普通插入方法:
public void insert(T element) {
Node in = new Node(element);
if (in == null) {
first = in;
} else {
Node tmp = first;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = in;
in.prec = tmp;
}
}
The idea is just to re-write the while loop with a function call: 这个想法只是用一个函数调用来重写while循环:
public void insert(T element) {
insert(element, first); // initialization
}
private void insert(T e, Node n) {
if(n == null) { // if the list is empty
first = new Node(e);
} else if(n.next == null) { // same condition as in the while loop
None newNode = new Node(e);
n.next = newNode;
newNode.prec = n;
} else {
insert(e, n.next); // looping
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.