Reputation: 1941
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;
}
}
Upvotes: 0
Views: 1657
Reputation: 53829
The idea is just to re-write the while loop with a function call:
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
}
}
Upvotes: 1