I am having trouble understanding how to deal with this off by one. Because if I decrease by one before the call I get a negative, which ruins everything. Static tail is not allowed, so do I need to create a previous Node each time?
public void recInsert(Object o, int index){
//No invalid inputs
if(index < 0){
throw new RuntimeException("Clearly out of bounds");
}
if(isEmpty() && index != 0){
throw new RuntimeException("Can't insert there on empty list");
}
recInsertHelper(index, o, head);
}
private void recInsertHelper(int index, Object o, Node current){
if(current == null){
throw new RuntimeException("too big");
}
if(index == 0){
current.next = new Node(o, current.next);
} else {
recInsertHelper(index-1, o, current.next);
}
}
I even tried changing base case to the answer @ Recursively add a node at a certain index on Linked List
acer + R, 0 = aRcer Should be Racer
Updated Code:
public void recInsert(Object o, int index){
//No invalid inputs
if(index < 0){
throw new RuntimeException("Clearly out of bounds");
}
if(isEmpty() && index != 0){
throw new RuntimeException("Can't insert there on empty list");
}
if(!isEmpty() && index == 0){
head = new Node(o, head);
} else {
recInsertHelper(index - 1, o, head);
}
}
private void recInsertHelper(int index, Object o, Node current){
if(current == null){
throw new RuntimeException("too big");
}
if(index == 0){
current.next = new Node(o, current.next);
} else {
recInsertHelper(index - 1, o, current.next);
}
}
Unfortunately, for a singly-linked list, insertion at an index works slightly differently than you're expecting. AS you can only insert forwards, insertions for a singly-linked list are a place ahead of where you would expect; as a result, you'll have to do an explicit check for if index
is 0. Long story short, index
is the node you're going to insert in front of.
So you'll need to do something like this in recInsert()
:
if (index == 0) {
// insert new node at head
else {
// Not inserting at head, so subtract 1 for "passing" head and continue
recInsertHelper(index - 1, o, head);
}
And I believe your recInsertHelper()
can stay the same, as you compensated for the offset in recInsert()
.